检查特定文件是否存在于指定驱动器上
我正在尝试写一个Python脚本,目的是扫描一个硬盘,看看在给定的文件列表中,有没有文件存储在这个硬盘上。如果找到了这些文件,就获取它们的位置。
我的编程技能说实话很基础。
在这个网站上,有人帮助我写了一个脚本,它可以找到一个文件,但我现在在调整这个脚本,让它能找到多个文件时遇到了困难。
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)
任何建议都非常感谢!
非常感谢。
1 个回答
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)
我还想说,可以考虑不断地写入文件,而不是把所有信息都存储在内存里,然后一次性写入:
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')
为什么呢?因为那些写操作系统的人对缓存的理解比我更深刻。