listdir 、getcwd、chdir的使用

来源:互联网 发布:java健身房信息系统 编辑:程序博客网 时间:2024/06/01 10:41
``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*
原创粉丝点击