Checking if multiple specific files exist on a given drive

2.5k views Asked by At

I'm attempting to write a Python script which scans a drive to check whether any files, from a given list, are stored somewhere on the drive. And, if they are found - retrieve their location.

My programming skills are basic, to put it nicely.

I've written a script, with the help of people on this website, which is able to locate a single file, but I am struggling to adapt it to find more than one file.

import os 

name = ('NEWS.txt') 
path = "C:\\"
result = [] 
for root, dirs, files in os.walk(path): 
    if name in files: 
        result.append(os.path.join(root, name) + "\n") 

f = open ('testrestult.txt', 'w') 
f.writelines(result)

Any advice would be appreciated!

Many thanks.

1

There are 1 answers

3
kojiro On BEST ANSWER
import os 

names = set(['NEWS.txt', 'HISTORY.txt']) # Make this a set of filenames 
path = "C:\\"
result = []
for root, dirs, files in os.walk(path): 
    found = names.intersection(files) # If any of the files are named any of the names, add it to the result.
    for name in found:
        result.append(os.path.join(root, name) + "\n") 

f = open ('testrestult.txt', 'w') 
f.writelines(result)

Tangent:

I would also consider writing to the file continuously, rather than storing up all the information in memory and doing a single write:

with open('testresult.txt', 'w') as f:
  for root, dirs, files in os.walk(path):
    found = names.intersection(files)
    for name in found:
      f.write(os.path.join(root, name) + '\n')

Why? Because the people who write operating systems understand buffering better than I do.