Python method to read all files in a system folder and count the number

  • 2020-12-22 17:43:56
  • OfStack

Let's look at part of the Python os module

python path-dependent functions

os.listdir(dirname) : Lists the directories and files under dirname

os. getcwd() : Gets the current working directory

os. curdir: Returns the current directory ('.')

os.chdir(dirname) : Change the working directory to dirname

os. path. isdir(name) : Determines if name is a directory and returns false if name is not

os. path. isfile(name) : determine if name is a file. name returns false if there is no file

os. path. exists(name) : Determines the existence of a file or directory name

os. path. getsize(name) : Gets the file size, returning 0 if name is a directory

os. path. abspath(name) : Obtain the absolute path

os. path. normpath(path) : Specifies the path string form

os. path. split(name) : Split the filename from the directory (in fact, if you use the directory entirely, it will also separate the last directory as the filename, and it will not determine whether the file or directory exists)

os. path. splitext() : Separate file name and extension

os. path. join(path,name) : Connect directories with filenames or directories

os. path. basename(path) : Returns the file name

os.path.dirname(path) : Returns the file path

The recursive search code is presented below (hidden files can be found, non-read-only files cannot be read, and such files are skipped with exception tests in the code)


import os

def visitDir(path):
 if not os.path.isdir(path):
 print('Error: "', path, '" is not a directory or does not exist.')
 return
 else:
 global x
 try:
  for lists in os.listdir(path):
  sub_path = os.path.join(path, lists)
  x += 1
  print('No.', x, ' ', sub_path)
  if os.path.isdir(sub_path):
   visitDir(sub_path)
 except:
  pass


if __name__ == '__main__':
 x = 0
 visitDir('H:\\Movie&Series')
 print('Total Permission Files: ', x)


Related articles: