SoFunction
Updated on 2024-10-30

Using Python to implement copying specified files from various subfolders

A small program that was used to organize pictures before, used as a memo, sort of an example of using Python to copy files.

# -*- coding: utf-8 -*-
# The program is used to copy files and output other information such as the date of the picture collection to Excel.
# 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 the _co.pgm data in each subfolder, in the Random1 folder
 
import os
import re
import xlwt
 
hang=0
# Recursive copying of files in a folder
def copyFiles(sourceDir,targetDir): 
 global hang   # Global variable to record the number of the row about to be written to Excel
 (hang, 0, label = sourceDir)
 for file in (sourceDir):
  frames = '('+file[('_')+1:]+')' # of data to be written to Excel
  sourceDir1 = (sourceDir,file) # pathname splicing
  targetDir1 = (targetDir,file)
  for file in (sourceDir1):
   sourceDir2 = (sourceDir1,file) 
   # Ignore certain subfolders
   if ("Random1")>0: 
   # List source directory files and folders
    count= -1
    for file in (sourceDir2): 
    #Splice the full path
     if ('_c0.pgm',file):
      count+=1
      sourceFile = (sourceDir2,file) 
      targetFile = (targetDir1,file) 
 
      if (sourceFile):
       if not (targetDir1):
        (targetDir1)
       if not (targetFile) or ((targetFile) and ((targetFile) != (sourceFile))):
        open(targetFile, "wb").write(open(sourceFile, "rb").read())
        print targetFile+" copy succeeded"
    frames = '0-'+str(count)+frames
    (hang, 1, label = 1)
    (hang, 2, label = frames)
    hang+=1
    print frames
 
workbook = ()
worksheet = workbook.add_sheet('My Worksheet')
copyFiles("F:/2016_07_07","F:/07_07")
('auto_book.xls')
print 'end'

The above method of using Python to realize the copying of specified files from various subfolders is all that I have shared with you.