1.遍历目录树
使用os.walk方法
>>> import os >>> for pathname,dirname,filename in os.walk("c:/Python34/TestDict"): print('path:'+pathname) print('dir:'+str(dirname)) print('file:'+str(filename)) path:c:/Python34/TestDict dir:['Test1', 'Test2'] file:['123.txt', 'input_file.txt', 'LICENSE.txt', 'NEWS.txt', 'output_file.txt', 'README.txt'] path:c:/Python34/TestDict\Test1 dir:[] file:['output_file.txt'] path:c:/Python34/TestDict\Test2 dir:[] file:['input_file.txt']
2.搜查某路径下所有个文件
>>> import os >>> for pathname,dirname,filename in os.walk("c:/Python34/TestDict"): if 'Test1' in pathname: print('path:'+pathname) print('dirs:'+str(dirname)) print('files:'+str(filename)) path:c:/Python34/TestDict\Test1 dirs:[] files:['output_file.txt'] >>>
>>> import os >>> def searchFile(keyWord,root): for pathname,dirname,filename in os.walk(root): if keyWord in pathname: print('path:'+pathname) print('dirs:'+str(dirname)) print('files:'+str(filename)) >>> searchFile('Test1',"c:/Python34/TestDict") path:c:/Python34/TestDict\Test1 dirs:[] files:['output_file.txt']
3.搜索某路径下某名字的文件
>>> def searchFile(keyWord,root): for path,subdirs,files in os.walk(root): #print(keyWord) #print(files) if keyWord in files: print(os.path.join(path,keyWord)) >>> searchFile("input_file.jpeg","c:/Python34/TestDict") c:/Python34/TestDict\input_file.jpeg c:/Python34/TestDict\Test2\input_file.jpeg >>>
4.批量修改某文件夹下某种文件的后缀
>>> import os >>> def swapFileExtendsion(root,oldExtends,newExtends): if oldExtends[:1]!='.': oldExtends='.'+oldExtends extendLength=-len(oldExtends) if newExtends[:1]!='.': newExtends='.'+newExtends for path,subdirs,files in os.walk(root): for oldFile in files: #print(oldFile [extendLength:]) #print(oldExtends) if oldFile [extendLength:]==oldExtends: oldFile=os.path.join(path,oldFile) newFile=oldFile[:extendLength]+newExtends os.rename (oldFile,newFile)
这个场景主要发生在服务器经常系统生产某些文件,而这些文件的后缀名错了,需要改过来
就说到这里,谢谢大家
------------------------------------------------------------------
点击跳转零基础学python-目录