This example describes how Python reads all directories and files in a directory. Share to everyone for your reference, as follows:
Here is a new Python read the list of reading, to share the following:
#!/usr/bin/python#-*-Coding:utf8-*-import osallfilenum = 0def Printpath (level, PATH): Global Allfilenum "Prints all the text in a directory folder and Files ' # All folders, the first field is the level of the secondary directory dirlist = [] # all Files fileList = [] # Returns a list containing the name of the directory entry (Google Translate) files = os.listdir (path) # First Add directory-level dirlist.append (str) to F in Files: if (os.path.isdir (path + '/' + f)): # Exclude hidden folders. Because there are too many hidden folders if (f[0] = = '. '): pass else: # Add a non-hidden folder dirlist.append (f) if (Os.path.isfile (path + '/' + f): # Add File filelist.append (f) # When a flag is used, the first level of the folder list 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 under Directory, directory level +1< C16/>printpath ((int (dirlist[0]) + 1), path + '/' + DL) for FL in fileList: # Prints the file Print '-' * (int (dirlist[0])), FL # Random calculation of how many files allfilenum = allfilenum + 1if __name__ = = ' __main__ ': Printpath (1, '/home/test/') print ' Total files = ', Allfilenum
More interested in Python related content readers can view the topic: "Python File and directory Operation skills 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 Summary, Python coding tips Summary, and Python introductory and advanced classic tutorials
I hope this article is helpful for Python program design.