Requirement: There are many subdirectories (for example, sections) under this directory, now all files with a. Meta extension are found from this directory and all subdirectories, and get the value of the second row GUID in the file (': '), and then output the value of all GUIDs to another file
. meta File:
Ideas:
Iterates through the subdirectory of the current directory, if it is a file and has a. meta extension, gets the GUID, writes to Guid.txt, or, if it is a subdirectory, traverses the files in the subdirectory.
Method One:
#!usr/bin/env python#-*-coding:utf-8-*-ImportOsoutfile= Open ('Guid.txt','a')#to open an output file in Append mode forDirinchOs.listdir ('.'):#Traverse Current Catalog All ask prices and directoriesChild = Os.path.join ('.', dir)#add path, otherwise not found ifOs.path.isdir (Child):#if it is a directory, continue traversing the subdirectories ' files forFileinchOs.listdir (Child):ifOs.path.splitext (file) [1] = ='. Meta':# split filename and file extension, and extension ' meta 'File = Os.path.join (child, file)# also add a path to thef = open (file,'R') GUID= F.readlines () [1].split (': ') [1]# gets the second line of the file with ': ' Split the latterOutfile.write (GUID)# Write output filef.close ()elifOs.path.isfile (Child):# if it is a file, the extension is directly judged ifOs.path.splitext (Child) [1] = ='. Meta': F= Open (Child,'R') GUID= F.readlines () [1].split (': ') [1] Outfile.write (GUID) f.close () outfile.close ()
Method Two: The above method can only traverse the level two directory, if you want to traverse the level three directory, you must also add a for loop. Then you can use the Os.walk () method to traverse the files and directories of the current directory and all subdirectories at once.
#!usr/bin/env python#-*-coding:utf-8-*-ImportOsoutfile= Open ('Guid.txt','a')#to open an output file in Append mode forDirpath, dirs, filesinchOs.walk ('.'):#recursively traverse files and directories of the current directory and all subdirectories forNameinchFiles#files are saved with all the file names ifOs.path.splitext (name) [1] = ='. Meta': FileName= Os.path.join (Dirpath, name)#add path, Dirpath is the path of the filef = open (filename,'R') GUID= F.readlines () [1].split (': ') [1]#gets the second line of the file with ': ' Split the latterOutfile.write (GUID)#Write output filef.close () outfile.close ( )
Run this program in this directory and you will get guid.txt.
The role and understanding of the relevant methods see: Http://www.cnblogs.com/victorwu/p/5838430.html
Python OS Module Instance traversal directory and subdirectories specify the file name extension