0

What is the best way to copy specific files from a list into a new directory using python?

For example, I have a text document containing file names like the below example:

E3004 
D0402 
B9404 
C6089

I would like to search a directory and copy the files that are found to exist into a new directory whilst listing the codes that are not found into a new text document.

I am a complete python novice, so any help is much appreciated.

Here's a piece of code from a previous discussion which was put together as a solution to a similar problem, however, I am having trouble understanding where exactly to place my file paths for the src, dst and text document? Furthermore, is there a way to save out the data which was not found to a separate text document?

Link to the previous discussion: https://stackoverflow.com/a/51621897/10580480

import os import shutil from tkinter import * from tkinter import filedialog

root = Tk()
 root.withdraw()

filePath = filedialog.askopenfilename()
 folderPath = filedialog.askdirectory()
 destination = filedialog.askdirectory()

filesToFind = []
 with open(filePath, "r") as fh:
    for row in fh:
        filesToFind.append(row.strip())

filename variable itself for filename in os.listdir(folderPath):
    if filename in filesToFind:
        filename = os.path.join(folderPath, filename)
        shutil.copy(filename, destination)
    else:
        print("file does not exist: filename")

Thanks

2 Answers2

0
for filename in os.listdir('/home/localDir/INPUT/'):
    if filename.startswith("localFileName"):
SuperKogito
  • 2,998
  • 3
  • 16
  • 37
  • 1
    Code only answers are discouraged on StackOverflow. Please consider adding some explanation to the code provided as it will benefit both OP and future visitors. – SuperKogito Apr 09 '19 at 12:01
  • While this code may solve the question, [including an explanation](https://meta.stackexchange.com/questions/114762/explaining-entirely-code-based-answers) of how and why this solves the problem would really help to improve the quality of your post, and probably result in more up-votes. Remember that you are answering the question for readers in the future, not just the person asking now. Please [edit] your answer to add explanation, and give an indication of what limitations and assumptions apply. – Dave Apr 09 '19 at 13:16
  • In my next answers, I will definitely improve my answers quality – Syed Zubair Ahamed Apr 10 '19 at 04:36
0

Using glob (see https://docs.python.org/3/library/glob.html) you can search for specific filenames in a directory - I have used it to find readme.md files from a git clones directory like:

for readmeFile in glob.glob('FULLPATH/clones/*/readme.md'):

so in your case: loop through your document containing filenames

for readmeFile in glob.glob('FULLPATH/clones/*/' + filename):