Home>

Here is an example of reading a directory when I just learned python.Share with you:

#!/usr/bin/python
#-*-coding:utf8-*-
import os
allfilenum=0
def printpath (level, path):
 global allfilenum
 "" "
 Print 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,Which contains the name of the directory entry (google translation)
 files=os.listdir (path)
 #Add directory level first
 dirlist.append (str (level))
 for 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 non-hidden folders
    dirlist.append (f)
  if (os.path.isfile (path + "/" + f)):
   #add files
   filelist.append (f)
 #When a flag is used,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 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 documents
  print "-" * (int (dirlist [0])), fl
  #Just count how many files there are
  allfilenum=allfilenum + 1
if __name__ == "__main__":
 printpath (1, "/home/test /")
 print "Total number of files =", allfilenum
  • Previous Graphic explanation of PHP environment building tutorial
  • Next Implementation method of custom paging for Yii view operation