1

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.

user2864740
  • 60,010
  • 15
  • 145
  • 220
teelos
  • 13
  • 1
  • 3
  • Are you aware of lists in python? I think all you need is a list of names and a `for` loop... – Dunno Mar 13 '14 at 18:31
  • possible duplicate of [How do I check if a file exists using Python?](http://stackoverflow.com/questions/82831/how-do-i-check-if-a-file-exists-using-python) – BoshWash Mar 13 '14 at 18:31

1 Answers1

4
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.

kojiro
  • 74,557
  • 19
  • 143
  • 201
  • Thanks for your reply, I tried running this but I'm getting an AttributeError: 'set' object has no attribute 'replace' – teelos Mar 13 '14 at 18:42
  • @teelos yes, I accidentally reused some names inappropriately. Try again. – kojiro Mar 13 '14 at 19:02
  • It works, thanks! Just had to remove the colon on line 7 as i got a syntax error. Thanks a lot. – teelos Mar 13 '14 at 19:08