本文内容涉及python中的os模块和os.path模块的常用操作,这两个模块提供了与平台和操作系统无关的文件系统访问方法。os模块负责大部分的文件系统操作,包括:删除文件、重命名文件、遍历目录树等;os.path模块提供了一些针对路径名的操作,包括:获取文件和子目录信息,文件路径查询等。
1. os模块
remove(path) 删除文件
rename(src,dst) 重命名文件
renames(old,new) 递归重命名目录或文件
walk(top,topdown=True,onerror=None,followlinks=False) 返回指定目录下每次遍历的路径名、目录列表、文件列表,top为指定的顶层目录,topdown表示自顶向下遍历,onerror指定异常函数,followlinks是否递归遍历链接文件。
chdir(path) 改变当前工作目录
listdir(path) 列出指定目录的文件和目录
getcwd() 返回当前工作目录
mkdir(path,mode=0o777) 创建目录
makedirs(path,mode=0o777) 递归创建目录
rmdir(path) 删除目录
removedirs(path) 递归删除目录
实例代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 | >>> import os>>> os.listdir('.')[]>>> os.mkdir('test1')>>> os.makedirs('test2/test21/test211')>>> os.listdir('.')['test2', 'test1']>>> os.listdir('./test2')['test21'] >>> open('test.txt','w')<open file 'test.txt', mode 'w' at 0x7faa26f69930>>>> os.listdir('.')['test2', 'test1', 'test.txt']>>> os.remove('test.txt')>>> os.listdir('.')['test2', 'test1']>>> os.getcwd()'/home/alexzhou/study_workspace/python/test'>>> os.chdir('./test1') >>> os.getcwd()'/home/alexzhou/study_workspace/python/test'>>> os.rename('test1','test3')>>> os.listdir('.')['test2', 'test3'] >>> os.renames('test2/test21/test211','test1/test11/test111')>>> os.listdir('.')['test1', 'test3']>>> os.listdir('test1')['test11']>>> os.listdir('test1/test11')['test111'] >>> open('test3/test.txt','w')<open file 'test3/test.txt', mode 'w' at 0x7faa26f69930>>>> for top,dirs,files in os.walk('.'):... print 'top:',top... print 'dirs:',dirs... print 'files:',files...top: .dirs: ['test1', 'test3']files: []top: ./test1dirs: ['test11']files: []top: ./test1/test11dirs: ['test111']files: []top: ./test1/test11/test111dirs: []files: []top: ./test3dirs: []files: ['test.txt'] >>> os.remove('test3/test.txt')>>> os.rmdir('test3')>>> os.listdir('.')['test1']>>> os.removedirs('test1/test11/test111')>>> os.listdir('.')[] |
2. os.path模块
basename(path) 去掉目录路径,返回文件名
dirname(path) 去掉文件名,返回目录路径
join(*path) 将分离的各部分组合成一个路径名
split(path) 返回(dirname(),basename())元组
splitdrive(path) 返回(drivename,pathname)元组
splitext(path) 返回(filename,extension)元组
exists(path) 指定文件或目录是否存在
isabs(path) 指定路径是否是绝对路径
isdir(path) 指定路径是否存在且是一个目录
isfile(path) 指定路径是否存在且是一个文件
islink(path) 指定路径是否存在且是一个符号链接
samefile(path1,path2) 两个路径名是否指向同一个文件
实例代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | >>> os.path.basename('/home/zhoujianghai/study_workspace/python/test_file.py')'test_file.py'>>> os.path.dirname('/home/zhoujianghai/study_workspace/python/test_file.py')'/home/zhoujianghai/study_workspace/python' >>> os.path.join('home','zhoujianghai','study_workspace')'home/zhoujianghai/study_workspace' >>> os.path.split('/home/zhoujianghai/study_workspace/python/test_file.py')('/home/zhoujianghai/study_workspace/python', 'test_file.py')>>> os.path.splitdrive('/home/zhoujianghai/study_workspace/python/test_file.py')('', '/home/zhoujianghai/study_workspace/python/test_file.py') >>> os.path.splitext('/home/zhoujianghai/study_workspace/python/test_file.py')('/home/zhoujianghai/study_workspace/python/test_file', '.py') >>> os.path.samefile('../test_file.py','../test_file.py')True>>> os.path.exists('../test_file.py')True |
下面是统计指定目录下文件数和代码行数的小例子
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | import sys,os def count_file_lines(filepath): ret = 0 f = open(filepath,"r") for lines in f: if lines.split(): ret += 1 return ret if __name__ == '__main__': top = './' total_lines = 0 total_files = 0 for root,dirs,files in os.walk(top): for filename in files: ext = os.path.splitext(filename)[-1] if ext in ['.py']: filepath = root + os.sep + filename total_files += 1 total_lines += count_file_lines(filepath) print 'Total lines:',total_lines print 'Total files: ',total_files |