8.6 操作系统文件处理

os模块对操作系统进行操作:

>>> import os
>>> dir(os)
['DirEntry', 'F_OK', 'MutableMapping', 'O_APPEND', 'O_BINARY', 'O_CREAT', 'O_EXCL', 'O_NOINHERIT', 'O_RANDOM', 'O_RDONLY', 'O_RDWR', 'O_SEQUENTIAL', 'O_SHORT_LIVED', 'O_TEMPORARY', 'O_TEXT', 'O_TRUNC', 'O_WRONLY', 'P_DETACH', 'P_NOWAIT', 'P_NOWAITO', 'P_OVERLAY', 'P_WAIT', 'PathLike', 'R_OK', 'SEEK_CUR', 'SEEK_END', 'SEEK_SET', 'TMP_MAX', 'W_OK', 'X_OK', '_Environ', '__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', '_execvpe', '_exists', '_exit', '_fspath', '_get_exports_list', '_putenv', '_unsetenv', '_wrap_close', 'abc', 'abort', 'access', 'altsep', 'chdir', 'chmod', 'close', 'closerange', 'cpu_count', 'curdir', 'defpath', 'device_encoding', 'devnull', 'dup', 'dup2', 'environ', 'errno', 'error', 'execl', 'execle', 'execlp', 'execlpe', 'execv', 'execve', 'execvp', 'execvpe', 'extsep', 'fdopen', 'fsdecode', 'fsencode', 'fspath', 'fstat', 'fsync', 'ftruncate', 'get_exec_path', 'get_handle_inheritable', 'get_inheritable', 'get_terminal_size', 'getcwd', 'getcwdb', 'getenv', 'getlogin', 'getpid', 'getppid', 'isatty', 'kill', 'linesep', 'link', 'listdir', 'lseek', 'lstat', 'makedirs', 'mkdir', 'name', 'open', 'pardir', 'path', 'pathsep', 'pipe', 'popen', 'putenv', 'read', 'readlink', 'remove', 'removedirs', 'rename', 'renames', 'replace', 'rmdir', 'scandir', 'sep', 'set_handle_inheritable', 'set_inheritable', 'spawnl', 'spawnle', 'spawnv', 'spawnve', 'st', 'startfile', 'stat', 'stat_float_times', 'stat_result', 'statvfs_result', 'strerror', 'supports_bytes_environ', 'supports_dir_fd', 'supports_effective_ids', 'supports_fd', 'supports_follow_symlinks', 'symlink', 'sys', 'system', 'terminal_size', 'times', 'times_result', 'truncate', 'umask', 'uname_result', 'unlink', 'urandom', 'utime', 'waitpid', 'walk', 'write']

8.6.1 常见函数列表

  • os.sep:返回操作系统特定的路径分隔符。
  • os.name:指示你正在使用的工作平台。比如对于Windows,它是'nt',而对于Linux/Unix用户,它是'posix'。
  • os.linesep:给出当前平台的行终止符。例如,Windows使用'\r\n',Linux使用'\n'而Mac使用'\r'。
  • os.curdir:返回当前目录('.')。
  • os.getcwd():得到当前工作目录,即当前Python脚本工作的目录路径。
  • os.getenv()os.putenv():读取和设置环境变量。
  • os.remove(file):删除一个文件。
  • os.stat(file):获得文件属性。
  • os.chmod(file):修改文件权限和时间戳。
  • os.rename(src, dst):重命名目录或文件夹。
  • os.mkdir(name):创建目录。
  • os.rmdir(name):删除目录。
  • os.removedirs(name):删除多个目录。
  • os.listdir(dirname):列出dirname下的目录和文件。
  • os.chdir(dirname):改变工作目录到dirname。
  • os.walk(dirname):遍历目录树,每次迭代返回一个元组 (dirpath, dirnames, filenames)
  • os.path.isdir(name):判断name是不是目录,不是目录就返回false。
  • os.path.isfile(name):判断name这个文件是否存在,不存在返回false。
  • os.path.exists(name):判断是否存在文件或目录name。
  • os.path.getsize(name):获得文件大小。
  • os.path.abspath(name):获得绝对路径。
  • os.path.isabs():判断是否为绝对路径。
  • os.path.normpath(path):规范path字符串形式。
  • os.path.split(name):分割文件名与目录(事实上,如果你完全使用目录,它也会将最后一个目录作为文件名而分离,同时它不会判断文件或目录是否存在)。
  • os.path.splitext():分离文件名和扩展名。
  • os.path.join(path,name):连接目录与文件名或目录。
  • os.path.basename(path):返回文件名。
  • os.path.dirname(path):返回文件路径。
  • os.system():运行shell命令。
  • os.exit():终止当前进程。

这些函数可以根据需要,对系统进行编程控制。

举例:

import os
# 对当前目录下,文件名包含dst的文件,移除dst和之后的部分
dst = ' - '

mov_list = []
for root, dirs, files in os.walk('.'):
    for file in files:
        mov_list.append(os.path.join(root, file))

mov_list = list(filter(lambda x: x.count(dst), mov_list))

for filename in mov_list:
    print('edit %s...' % filename)
    base_name = os.path.splitext(filename)[0]
    ext = os.path.splitext(filename)[1]
    new_name = f"{base_name.partition(dst)[0]}{ext}"
    os.rename(filename, new_name)