10.1 操作系统概览 Operating System Interface

The os module provides dozens of functions for interacting with the operating system:

os 模块提供了不少与操作系统相关联的函数。

>>> import os
>>> os.system('time 0:02')
0
>>> os.getcwd()      # Return the current working directory
'C:\\Python24'
>>> os.chdir('/server/accesslogs')

Be sure to use the "import os" style instead of "from os import *". This will keep os.open() from shadowing the builtin open() function which operates much differently.

应该用 "import os" 风格而非 "from os import *"。这样可以保证随操作系统不同而有所变化的 os.open() 不会覆盖内置函数 open()

The builtin dir() and help() functions are useful as interactive aids for working with large modules like os:

在使用一些像 os 这样的大型模块时dir()help() 函数非常有用。

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

For daily file and directory management tasks, the shutil module provides a higher level interface that is easier to use:

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

>>> import shutil
>>> shutil.copyfile('data.db', 'archive.db')
>>> shutil.move('/build/executables', 'installdir')