Python之OS(系统操作)模块常用函数

mkdir(path[, mode=0777])

makedirs(name,mode=511)

rmdir(path)

removedirs(path)

listdir(path)

getcwd()

chdir(path)

walk(top, topdown=True, onerror=None)  返回一个元组:(遍历的路径,目录,文件列表)

 


我们来遍历一下文件:

 1 >>> for path, dir, filename in os.walk('/home/branches/python/testdir'):
 2 ...     for filen in filename:
 3 ...             os.path.join(path, filen)
 4 ... 
 5 '/home/branches/python/testdir/f1'
 6 '/home/branches/python/testdir/f2'
 7 '/home/branches/python/testdir/f3'
 8 '/home/branches/python/testdir/jpg/0.ipg'
 9 '/home/branches/python/testdir/jpg/3.ipg'
10 '/home/branches/python/testdir/jpg/2.ipg'
11 '/home/branches/python/testdir/jpg/1.ipg'
12 '/home/branches/python/testdir/jpg/get_img.py'
13 >>> 
14 >>> 
15 >>> 
16 >>> for path, dir, filename in os.walk('testdir'):
17 ...     for filen in filename:
18 ...             os.path.join(path, filen)
19 ... 
20 'testdir/f1'
21 'testdir/f2'
22 'testdir/f3'
23 'testdir/jpg/0.ipg'
24 'testdir/jpg/3.ipg'
25 'testdir/jpg/2.ipg'
26 'testdir/jpg/1.ipg'
27 'testdir/jpg/get_img.py'
28 >>> 
 1 #!/usr/bin/python
 2 #coding:utf8
 3 
 4 import os
 5 
 6 def dirList(path):      # 列出当前目录下的完整路径名
 7         filelist = os.listdir(path)
 8         # fpath = os.getcwd()   # 它获取的是程序所在路径
 9         allfile = []
10         for filename in filelist:
11                 # allfile.append(fpath  + '/' + filename)
12                 filepath = os.path.join(path, filename) # 用os模块的方法进行路径拼接
13                 if os.path.isdir(filepath):
14                         dirList(filepath)
15                 print filepath  
16 
17 allfile = dirList('/home/branches/python/testdir')

 

posted on 2017-06-12 20:37  枝桠  阅读(163)  评论(0编辑  收藏  举报

导航