mgri
mgri

Reputation: 267

Copying thousands of files (filtered by name) to a specified folder

I'm trying to run two operations:

  1. Starting from a .txt file containing some IDs (which lead to a filename), checking if that file is within a folder;
  2. If step 1) is true, copying the file from that folder to a specified folder.

The .txt file stores codes like these:

111081
112054
112051
112064

This is what I have tried:

from glob import glob
from shutil import copyfile
import os

input = 'C:/Users/xxxx/ids.txt'
input_folder = 'C:/Users/xxxx/input/'
dest_folder = 'C:/Users/xxxx/output/'
with open(input) as f:
   for line in f:
       string = "fixed_prefix_" + str(line.strip()) + '.asc'
       if os.path.isfile(string):
            copyfile(string, dest_folder)

The string variable generates this (for example):

print string
fixed_prefix_111081.asc

Then, I'm sure there is something else wrong with the searching and the copying of the file to the destination folder. The main problem is that I don't know how to search for the fixed_prefix_111081.asc file in the input_folder.

Upvotes: 2

Views: 103

Answers (1)

Jean-François Fabre
Jean-François Fabre

Reputation: 140168

  • copyfile expects a filename as destination. Passing an existing directory is the case where it doesn't work. Using copy handles both cases (target directory or target file)
  • the input file seems to be passed without path. You'd have to generate the full filename if you're not in input_folder or os.path.isfile will always be False

My fix proposal:

with open(input) as f:
   for line in f:
       string = "fixed_prefix_{}.asc".format(line.strip())
       fp_string = os.path.join(input_folder,string)
       if os.path.isfile(fp_string):
            copy(fp_string, dest_folder)

Upvotes: 2

Related Questions