Python - Folder Actions

Python folder / file operations

1, os.listdir () - Returns the current folder for all directory names (list)

2, os.walk () - traversing the directory tree, the directory name in the output file, and returns a triplet (root, dirs, files)

  • root referring to the address currently traversing the folder itself
  • dirs is a list, all content is the name of the directory folder (not including subdirectories)
  • files also list, the contents of that folder are all the files (not including subdirectories)

      '''
      def copy_file(old_file, new_file):
          new_file_temp = new_file
          for root, dirs, files in os.walk(old_file, topdown=False):
              for name in files:
                  sub_path = root.split('\\')[-1]
                  sub_sub_path = root.split('\\')[-2]
                  if sub_path == 'R0':
                      sub_path_new = '5'
                  elif sub_path == 'R1':
                      sub_path_new = '6'
                  elif sub_path == 'R2':
                      sub_path_new = '7'
    
                  verify_or_enroll = ''
                  if(int(name.split('.')[0]) < 1):
                      verify_or_enroll = 'enroll'
                  elif(int(name.split('.')[0]) >= 1 ):
                      verify_or_enroll = 'verify'
    
                  new_file_path = os.path.join(new_file_temp, sub_sub_path, sub_path_new, verify_or_enroll, 'st')
                  if not os.path.exists(new_file_path):
                      os.makedirs(new_file_path)
                  new_file_name = os.path.join(new_file_path, name)
                  old_file_name = os.path.join(root, name)
                  shutil.copyfile(old_file_name, new_file_name)
                  print(old_file_name, 'to', new_file_name)
      '''
    

    summary:

    • walk in the topdown parameter to False when traversing approach is to start from the child file, directory root obtained at this time is the child file is located, files is the same sub-folder list of file names consisting of
    • After completion subfile traversal, up traversal, then empty files, the iteration is complete

Guess you like

Origin www.cnblogs.com/first-try/p/11300740.html