This example describes how Python reads all directories and files in a directory. Share to everyone for your reference, specific as follows:
Here is a reading of the directory when just learning Python, to share the following:
#!/usr/bin/python #-*-Coding:utf8-*-import os allfilenum = 0 def printpath (level, path ): Global allfilenum ' Prints all folders and files in a directory ' # all folders, the first field is the level of the secondary directory dirlist = [] # all files filelist = [] # Returns a list where the package Include the name of the directory entry (Google translator) files = Os.listdir (path) # First add the directory level Dirlist.append (str) to F in Files:if (Os.path.isdir p Ath + '/' + F): # Exclude hidden folders.
Because there are too many hidden folders if (f[0] = = '. '): Pass else: # Add hidden folders dirlist.append (f) if (os.path.isfile (path + '/' + f)): # Add File Filelist.append (f) # When a flag is used, the folder list first level does not print I_DL = 0 for DL in dirlist:if (I_DL = = 0): I_dl = I_dl + 1 Else: # Print to the console, not the first directory print '-' * (int (dirlist[0]), DL # Print all folders and files in the directory, directory level +1 printpath (int (dirlist[0 ] + 1), path + '/' + DL ' for FL in filelist: # Print file print '-' * (int (dirlist[0]), FL # Just calculate how many files Allfilenum = Allfilenum + 1 if __name__ = = ' __main__ ': Printpath (1, '/home/test/') print ' total file Number = ', Allfilenum
More information about Python-related content can be viewed in this site: "Python file and directory operation tips Summary", "Python Picture Operation skills Summary", "Python data structure and algorithm tutorial", "Python Socket Programming Skills Summary", " Python function Usage Tips Summary, python string manipulation tips, Python code manipulation tips and Python introductory and advanced classic tutorials
I hope this article will help you with Python programming.