Python's operations summary of folders for easy access to
1. Traverse the specified directory to display all file names under the directory
#-*-coding:utf-8-*-import osdef fileinfolder (filepath): pathdir = os.listdir (filepath) # Get all files under the filepath folder file = [] for Alldir in pathdir: Child = Os.path.join ('%s\\%s '% (filepath, alldir)) C6/>files.append (Child.decode (' GBK ')) #. Decode (' GBK ') is a solution to the Chinese display garbled problem # print Child # if Os.path.isdir ( Child): # Print Child # Simplepath = os.path.split (Child) # Print Simplepath return Filesfilepath = "C:\\files" Print fileinfolder (filepath) output: [u ' c:\\files\\a.txt ', U ' c:\\files\\b.txt ', U ' C:\\files\\c ']
2. Traverse all files of the folder and its subfolders to get a list of the files
#-*-coding:utf-8-*-import osdef getfilelist (filepath): filelist = os.listdir (filepath) # Get all files under the filepath folder file = [] for I in range (len (filelist)): Child = Os.path.join ('%s\\%s '% (filepath, Filelist[i]) if Os.path.isdir (child): files.extend (getfilelist (child)) else: files.append ( Child) return filesfilepath = "C:\\files" Print getfilelist (filepath) output: [' c:\\files\\a.txt ', ' c:\\files\\b.txt ' , ' C:\\files\\c\\d.txt ', ' c:\\files\\c\\e.txt ', ' c:\\files\\c\\f\\g.txt ']
3. Python traverses the sub-file and all subfolder output strings
Reference: http://blog.csdn.net/Qian_F/article/details/9896283
#-*-coding:utf-8-*-import osdef getfilelist (filepath, tabnum=1): Simplepath = os.path.split (filepath) [1] RETURNSTR = simplepath+ "directory <>" + "\ n" returndirstr = "" returnfilestr = "" filelist = Os.listdir ( filepath) for num in range (len (filelist)): Filename=filelist[num] if Os.path.isdir (filepath+ "/" + FileName): returndirstr + = "\ T" *tabnum+getfilelist (filepath+ "/" +filename, tabnum+1) else: Returnfilestr + = "\ t" *tabnum+filename+ "\ n" returnstr + = returnfilestr+returndirstr return returnstr+ "\ T" * tabnum+ "</>\n" filepath = "c:\\files" f = open ("Test.xml", "w+") F.writelines (Getfilelist (filepath)) F.close ()
4. Batch renaming of documents
#-*-coding:utf-8-*-import osdef filesrename (filepath): filelist = os.listdir (filepath) # Get all files under the filepath folder file = [] for I in range (len (filelist)): Child = Os.path.join ('%s\\%s '% (filepath, Filelist[i]) if Os.path.isdir (child): continue Else: newName = Os.path.join ('%s\\%s '% (filepath, STR (i) + "_" + Filelist[i])) print newName os.rename (Child, newName) filepath = "C:\\files2" Filesrename ( FilePath
Python Action folder