Use Python to implement a method for copying a specified file from each subfolder

  • 2021-01-02 21:56:13
  • OfStack

An example of using Python to copy files is a small program used to organize images.


# -*- coding: utf-8 -*-
# The program is used to copy files and output pictures acquisition date and other information to Excel In the 
# Folder structure: 
#2016_07_07
#  -Data_07_07_001
#   -Random1
#    -image001_co.pgm
#    -image001_c1.pgm
#    -image002_co.pgm
#    -image002_c1.pgm
#    - ... 
#   -Random2
#   - ... 
#  -Data_07_07_002
#  -Data_07_07_003
#  - ... 
# So we just copy each of these subfolders, Random1 In a folder _co.pgm data 
 
import os
import re
import xlwt
 
hang=0
# Recursively copies the files in the folder 
def copyFiles(sourceDir,targetDir): 
 global hang   # Global variable, the record is about to be written Excel The line number 
 worksheet.write(hang, 0, label = sourceDir)
 for file in os.listdir(sourceDir):
  frames = '('+file[file.find('_')+1:]+')' # To be written to the Excel The data in the 
  sourceDir1 = os.path.join(sourceDir,file) # Pathname splicing 
  targetDir1 = os.path.join(targetDir,file)
  for file in os.listdir(sourceDir1):
   sourceDir2 = os.path.join(sourceDir1,file) 
   # Ignore certain subfolders 
   if sourceDir2.find("Random1")>0: 
   # Lists the source directory files and folders 
    count= -1
    for file in os.listdir(sourceDir2): 
    # Splicing complete path 
     if re.search('_c0.pgm',file):
      count+=1
      sourceFile = os.path.join(sourceDir2,file) 
      targetFile = os.path.join(targetDir1,file) 
 
      if os.path.isfile(sourceFile):
       if not os.path.exists(targetDir1):
        os.makedirs(targetDir1)
       if not os.path.exists(targetFile) or (os.path.exists(targetFile) and (os.path.getsize(targetFile) != os.path.getsize(sourceFile))):
        open(targetFile, "wb").write(open(sourceFile, "rb").read())
        print targetFile+" copy succeeded"
    frames = '0-'+str(count)+frames
    worksheet.write(hang, 1, label = 1)
    worksheet.write(hang, 2, label = frames)
    hang+=1
    print frames
 
workbook = xlwt.Workbook()
worksheet = workbook.add_sheet('My Worksheet')
copyFiles("F:/2016_07_07","F:/07_07")
workbook.save('auto_book.xls')
print 'end'

Related articles: