``os``
模块
也包含了
一些用于目录处理的
函数.
``listdir`` 函数返回给定目录中所有文 件名(包括目录名)组成的列表, 如
[Example 1-28 #eg-1-28] 所 示. 而 Unix 和 Windows 中使用的当 前目录和父目录标记(. 和 .. )不包含在 此列表中.
====Example 1-28. 使用 os 列出目录 下的文 件====[eg-1-28]
```
File: os-example-5.py
import os
for file in os.listdir("samples"):
print file
*B*sample.au
sample.jpg
sample.wav
... *b *
```
``getcwd`` 和 ``chdir`` 函数 分别用于获得和改变当 前工作目录. 如 [Example 1-29 #eg-1-29] 所 示.
====Example 1-29. 使用 os 模块改变当 前工作目录====[eg-1-29]
```
File: os-example-4.py
import os
# where are we ?
cwd = os.getcwd()
print "1", cwd
# go down
os.chdir("samples")
print "2", os.getcwd()
# go back up
os.chdir(os.pardir)
print "3", os.getcwd()
*B*1 /ematter/librarybook
2 /ematter/librarybook/samples
3 /ematter/librarybook*b*
``listdir`` 函数返回给定目录中所有文 件名(包括目录名)组成的列表, 如
[Example 1-28 #eg-1-28] 所 示. 而 Unix 和 Windows 中使用的当 前目录和父目录标记(. 和 .. )不包含在 此列表中.
====Example 1-28. 使用 os 列出目录 下的文 件====[eg-1-28]
```
File: os-example-5.py
import os
for file in os.listdir("samples"):
print file
*B*sample.au
sample.jpg
sample.wav
... *b *
```
``getcwd`` 和 ``chdir`` 函数 分别用于获得和改变当 前工作目录. 如 [Example 1-29 #eg-1-29] 所 示.
====Example 1-29. 使用 os 模块改变当 前工作目录====[eg-1-29]
```
File: os-example-4.py
import os
# where are we ?
cwd = os.getcwd()
print "1", cwd
# go down
os.chdir("samples")
print "2", os.getcwd()
# go back up
os.chdir(os.pardir)
print "3", os.getcwd()
*B*1 /ematter/librarybook
2 /ematter/librarybook/samples
3 /ematter/librarybook*b*