Python reads all directories and files in a directory _python

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.