-1

New to Python... I'm trying to have python take a text file of file names (new name on each row), and store them as strings ...

i.e

import os, shutil       
files_to_find = []
with open('C:\\pathtofile\\lostfiles.txt') as fh:
    for row in fh:
        files_to_find.append(row.strip)

...in order to search for these files in directories and then copy any found files somewhere else...

for root, dirs, files in os.walk('D:\\'):
for _file in files:
    if _file in files_to_find:
       print ("Found file in: " + str(root))
        shutil.copy(os.path.abspath(root + '/' + _file), 'C:\\destination')

print ("process completed")

Despite knowing these files exist, the script runs without any errors but without finding any files.

I added...

print (files_to_find)

...after the first block of code to see if it was finding anything and saw screeds of "built-in method strip of str object at 0x00000000037FC730>,

Does this tell me it's not successfully creating strings to compare file names against? I wonder where I'm going wrong?

Harley
  • 1

1 Answers1

-1

Use array to create a list of files.

import os
import sys
import glob
import shutil


def file_names(self,filepattern,dir):
    os.chdir(dir)
    count = len(glob.glob(filepattern))
    file_list = []
    for line in sorted(glob.glob(filepattern)):
        line = line.split("/")
        line = line[-1]
        file_list.append(line)
    return file_list 

The loop over the array list to compare.