Python script for moving directories/files while ignoring certain directories/files using shutil?

StackOverflow https://stackoverflow.com/questions/13256243

  •  27-11-2021
  •  | 
  •  

Question

I'm looking to build a python script that moves files/directories from one directory to another while referencing a list that notes the files to be copied over.

Here is what I have thus far:

import os, shutil

// Read in origin & destination from secrets.py Readlines() stores each line followed by a '/n' in a list

    f = open('secrets.py', 'r')
    paths = f.readlines()

// Strip out those /n

    srcPath = paths[0].rstrip('\n')
    destPath = paths[1].rstrip('\n')

// Close stream

    f.close()

// Empty destPath

    for root, dirs, files in os.walk(destPath, topdown=False):
        for name in files:
            os.remove(os.path.join(root, name))
        for name in dirs:
            os.rmdir(os.path.join(root, name))

// Copy & move files into destination path

    for srcDir, dirs, files in os.walk(srcPath):
        destDir = srcDir.replace(srcPath, destPath)
        if not os.path.exists(destDir):
            os.mkdir(destDir)
        for file in files:
            srcFile = os.path.join(srcDir, file)
            destFile = os.path.join(destDir, file)
            if os.path.exists(destFile):
                os.remove(destFile)
            shutil.copy(srcFile, destDir)

The secrets.py files contains the src/dest paths.

Currently this transfers all files/directories over. I'd like to read in another file that allows you to specify which files to transfer (rather than making a "ignore" list).

Était-ce utile?

La solution

You should read the file list

 f = open('secrets.py', 'r')
 paths = f.readlines()

 f_list = open("filelist.txt", "r")
 file_list = map(lambda x: x.rstrip('\n'), f_list.readlines())

 ....
 ....

and check before copying

    for file in files: 
       if file in file_list# <--- this is the condition you need to add to your code
          srcFile = os.path.join(srcDir, file)
       ....

if your file list contains pattern of file names to be copied try using "re" module of python to match your file name.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top