Today, using Python to extract the Linux kernel source directory tree structure, not how to write a script, I actually toss 2 hours, first how to enumerate all the files and folders in a given directory, Os.walk can be enumerated, but Os.walk is given only the directory name and file name, not the absolute path. Use Os.path.listdir can do this, and then create a directory, because when the directory is prompted to create a failure error, so I would like to delete all directories, and then create, but found that there is still a problem, it is best to use the judgment if it does not exist to create the directory, when it exists, do not create, paste the code:
# @This script can used to iterate the given Directory,and create the # empty directory structure without file in I T,e.g,i want to has you directory# as the Linux kernel source, but I don ' t want the files and then this script comes.# @ This script is running under Python 3.1# @author: zhangchao# @Time: July 25, 2011 18:43:26################################## ######################################## #import Osimport Re#listmydirs is created to recursivly list all the Entrys in the Specified path. #In fact, we have os.walk to handle this problem# #level: The number of layers of the directory, not to be able, mainly to show the directory at that level #srcpath: The path of the kernel source code # DestPath: The directory structure of the kernel source code that will be generated is located in the path #def createkerneldirs (Level,srcpath,destpath): For Entrys in Os.listdir (Srcpath): # Learn the usage of the Listdir function Tmpsrcpath=srcpath+os.sep+entrys Tmpdestpath = tmpsrcpath.replace (srcpath,destpath) #将源路径中的E: \ linux-2.6 Replace with E:\tmp, learn the use of the string substitution function print (' At level: ' +str (level)) ' Print (tmpsrcpath) print (Tmpdestpath) If Os.path.isdir (tmpsRcpath): Listmydirs (Level+1,tmpsrcpath,tmpdestpath) if os.path.exists (Tmpdestpath) ==false: #如果文件不存在才 Create File Os.makedirs (tmpdestpath) if __name__== ' __main__ ': #将E: \linux-2.6 Kernel source directory structure copied to E:\tmp directory Createkerneldi RS (1,r ' E:\linux-2.6 ', R ' E:\tmp ')
Python Extracts the directory structure of the Linux kernel source code