10.1. 操作系统接口

os 模块提供了许多与操作系统交互的函数:

  1. >>> import os
  2. >>> os.getcwd() # Return the current working directory
  3. 'C:\\Python38'
  4. >>> os.chdir('/server/accesslogs') # Change current working directory
  5. >>> os.system('mkdir today') # Run the command mkdir in the system shell
  6. 0

一定要使用 import os 而不是 from os import * 。这将避免内建的 open() 函数被 os.open() 隐式替换掉,它们的使用方式大不相同。

内置的 dir()help() 函数可用作交互式辅助工具,用于处理大型模块,如 os:

  1. >>> import os
  2. >>> dir(os)
  3. <returns a list of all module functions>
  4. >>> help(os)
  5. <returns an extensive manual page created from the module's docstrings>

对于日常文件和目录管理任务, shutil 模块提供了更易于使用的更高级别的接口:

  1. >>> import shutil
  2. >>> shutil.copyfile('data.db', 'archive.db')
  3. 'archive.db'
  4. >>> shutil.move('/build/executables', 'installdir')
  5. 'installdir'