python os 模块常用操作

时间:2022-05-24 23:59:54

python 2.7 os 常用操作

官方document链接

文件和目录

  • os.access(path, mode) 读写权限测试
应用:
try:
fp = open("myfile")
except IOError as e:
if e.errno == errno.EACCES:
return "some default data"
# Not a permission error.
raise
else:
with fp:
return fp.read() 模式说明: os.F_OK
Value to pass as the mode parameter of access() to test the existence of path. os.R_OK
Value to include in the mode parameter of access() to test the readability of path. os.W_OK
Value to include in the mode parameter of access() to test the writability of path. os.X_OK
Value to include in the mode parameter of access() to determine if path can be executed.
  • os.chdir(path) 改变目录
  • os.getcwd() 获取当前工作目录
  • os.listdir(path) 列出目录中的文件,不包含'.' 和 '..'
  • os.mkdir(path[, mode]) 创建单个目录,可以添加文件夹的读写属性
Create a directory named path with numeric mode mode. The default mode is 0777 (octal). If the directory already exists, OSError is raised
  • os.makedirs(path[, mode]) 创建多级目录
  • os.remove(path) 删除文件
Remove (delete) the file path. If path is a directory, OSError is raised; see rmdir() below to remove a directory. This is identical to the unlink() function documented below. On Windows, attempting to remove a file that is in use causes an exception to be raised; on Unix, the directory entry is removed but the storage allocated to the file is not made available until the original file is no longer in use.
  • os.removedirs(path) 删除多级目录
Remove directories recursively. Works like rmdir() except that, if the leaf directory is successfully removed, removedirs() tries to successively remove every parent directory mentioned in path until an error is raised (which is ignored, because it generally means that a parent directory is not empty). For example, os.removedirs('foo/bar/baz') will first remove the directory 'foo/bar/baz', and then remove 'foo/bar' and 'foo' if they are empty. Raises OSError if the leaf directory could not be successfully removed.
  • os.rmdir(path) 删除目录,只有目录是空的时候,才有作用
Remove (delete) the directory path. Only works when the directory is empty, otherwise, OSError is raised. In order to remove whole directory trees, shutil.rmtree() can be used.
  • os.rename(src, dst) 文件重命名
Rename the file or directory src to dst. If dst is a directory, OSError will be raised. On Unix, if dst exists and is a file, it will be replaced silently if the user has permission. The operation may fail on some Unix flavors if src and dst are on different filesystems. If successful, the renaming will be an atomic operation (this is a POSIX requirement). On Windows, if dst already exists, OSError will be raised even if it is a file; there may be no way to implement an atomic rename when dst names an existing file.
  • os.renames(old, new) 多级目录重命名
Recursive directory or file renaming function. Works like rename(), except creation of any intermediate directories needed to make the new pathname good is attempted first. After the rename, directories corresponding to rightmost path segments of the old name will be pruned away using removedirs().

系统操作

  • os.system(command) 执行命令行操作

subprocess 可以提供更加强大的功能

On Unix, the return value is the exit status of the process encoded in the format specified for wait(). Note that POSIX does not specify the meaning of the return value of the C system() function, so the return value of the Python function is system-dependent.

On Windows, the return value is that returned by the system shell after running command, given by the Windows environment variable COMSPEC: on command.com systems (Windows 95, 98 and ME) this is always 0; on cmd.exe systems (Windows NT, 2000 and XP) this is the exit status of the command run; on systems using a non-native shell, consult your shell documentation.

假如要执行多个命令,则需要在每个命令后加 '&'

应用:
>>> command = "cd D:\\LearnPython\\base & dir"
>>> os.system(command)

通用路径名操作 os.path

官方文档链接

  • os.path.abspath(path) 返回当前目录的绝对路径
  • os.path.basename(path) 返回路径中的基础名
>>> os.path.basename('D:\\LearnPython\\base')
'base'
  • os.path.dirname(path) 返回当前文件夹的上层路径名
>>> os.path.dirname('D:\\LearnPython\\base')
'D:\\LearnPython'
  • os.path.exists(path) 检查路径是否存在,可用于检查目录或文件是否存在
>>> os.path.exists('D:\\LearnPython\\base')
True
>>> os.path.exists('D:\\LearnPython\\base\\wrn_log.py')
True
>>> os.path.exists('D:\\LearnPython\\base\\wrn_log.pyy')
False
  • os.path.getsize(path) 获取文件大小,单位bytes
>>> os.path.getsize('D:\\LearnPython\\base\\wrn_log.py')
1307L
  • os.path.isabs(path) 判断是否是绝对路径

  • os.path.isfile(path) 判断path中的是否是一个已经存在的文件

  • os.path.isdir(path) 判断是否为一个已经存在的目录

  • os.path.join(path, *paths) 对目录路径进行拼接

Join one or more path components intelligently. The return value is the concatenation of path and any members of *paths with exactly one directory separator (os.sep) following each non-empty part except the last, meaning that the result will only end in a separator if the last part is empty. If a component is an absolute path, all previous components are thrown away and joining continues from the absolute path component.
On Windows, the drive letter is not reset when an absolute path component (e.g., r'\foo') is encountered. If a component contains a drive letter, all previous components are thrown away and the drive letter is reset. Note that since there is a current directory for each drive, os.path.join("c:", "foo") represents a path relative to the current directory on drive C: (c:foo), not c:\foo.
应用:
>>> p = os.path.join("d:\\", "LearnPython\\base")
>>> p
'd:\\LearnPython\\base'
  • os.path.split(path) 对路径进行分割,返回一个tuple(head, tail),和join可以对应
>>> s = os.path.split("d:\\LearnPython\\base")
>>> s
('d:\\LearnPython', 'base')
  • os.path.splitdirve(path) 对路径进行分割,但可以分离出驱动盘
>>> s = os.path.splitdrive("d:\\LearnPython\\base")
>>> s
('d:', '\\LearnPython\\base')
  • os.path.splitext(path) 分割扩展名
>>> s = os.path.splitext("d:\\LearnPython\\base\\wrn_log.py")
>>> s
('d:\\LearnPython\\base\\wrn_log', '.py')
  • os.path.walk(path, visit, arg) 获取目录树。在Py3中已经改为os.walk()
import os
from os.path import join, getsize
for root, dirs, files in os.walk('python/Lib/email'):
print root, "consumes",
print sum(getsize(join(root, name)) for name in files),
print "bytes in", len(files), "non-directory files"
if 'CVS' in dirs:
dirs.remove('CVS') # don't visit CVS directories