Swan87
Swan87

Reputation: 421

Search for multiple files by name and copy to a new folder

I have been trying to write some python code in order to get each line from a .txt file and search for a file with that name in a folder and its subfolders. After this I want to copy that file in a preset destination folder.

The thing is when I test this code I can read all the files in the .txt and I can display all files in a directory and its subdirectories. The problem rises when I have to compare the filename I read from the .txt (line by line as I said) with all the filenames within the directory folder and then copy the file there.

Any ideas what am I doing wrong?

import os, shutil

def main():

dst = '/Users/jorjis/Desktop/new'

f = open('/Users/jorjis/Desktop/articles.txt', 'rb')
lines = [line[:-1] for line in f]
for files in os.walk("/Users/jorjis/Desktop/folder/"):
    for line in lines:
        if line == files:
            shutil.copy('/dir/file.ext', '/new/dir')

Upvotes: 1

Views: 4297

Answers (2)

BlackJack
BlackJack

Reputation: 4679

You are comparing the file names from the text file with a tuple with three elements: the root path of the currently visited folder, a list of all subdirectory names in that path, and a list of all file names in that path. Comparing a string with a tuple will never be true. You have to compare each file name with the set of file names to copy. The data type set comes in handy here.

Opening a file together with the with statement ensures that it is closed when the control flow leaves the with block.

The code might look like this:

import os
import shutil

def main():
    destination = '/Users/jorjis/Desktop/new'

    with open('/Users/jorjis/Desktop/articles.txt', 'r') as lines:
        filenames_to_copy = set(line.rstrip() for line in lines)

    for root, _, filenames in os.walk('/Users/jorjis/Desktop/folder/'):
        for filename in filenames:
            if filename in filenames_to_copy:
                shutil.copy(os.path.join(root, filename), destination)

Upvotes: 1

Al.Sal
Al.Sal

Reputation: 984

If I had to guess, I would say that the files in the .txt contain the entire path. You'd need to add a little more to os.walk to match up completely.

for root, _, files in os.walk("/Users/jorjis/Desktop/folder/"):
    for f in files:
        new_path = f + root
        if new_path in lines:
            shutil.copy(new_path, `/some_new_dir')

Then again, I'm not sure what the .txt file looks like so it might be that your original way works. If that's the case, take a closer look at the lines = ... line.

Upvotes: 0

Related Questions