[英]Python search multiple hard drives
我正在尝试编写一个简单的脚本来搜索我的本地驱动器 C: 和我的两个外部驱动器 E: 和 F: 以获取所有 .docx 文件并将它们写入日志。 我有搜索部分,但一次只能搜索一个硬盘驱动器,无法弄清楚如何将结果写入 .log 或 .txt 文件。 这是我的起始代码:它没有错误
import fnmatch
import os
rootPath = 'F:'
pattern = "*.docx"
for root, dirs, files in os.walk(rootPath):
for filename in fnmatch.filter(files, pattern):
print( os.path.join(root, filename))
import fnmatch
import os
drives = ['C:\\','E:\\','F:\\']
pattern = "*.docx"
for rootPath in drives:
print "Now searching in: ",rootPath
for root, dirs, files in os.walk(rootPath) :
for filename in fnmatch.filter(files, pattern) :
print os.path.join(root, filename)
将结果写入文件,如下所示:
with open("log.txt","wb") as fs:
result = "whatever result you are getting"
fs.write(result)
更新:
import fnmatch
import os
drives = ['C:\\','E:\\','F:\\']
pattern = "*.py"
with open("log.txt","wb") as fs:
for rootPath in drives:
print "Now searching in: ",rootPath
for root, dirs, files in os.walk(rootPath) :
for filename in fnmatch.filter(files, pattern) :
print os.path.join(root, filename)
result = os.path.join(root, filename)
fs.write(result+"\n")
尝试自己编写代码,然后查看解决方案。
请询问您是否有什么不明白的地方。
另请参阅此问题以了解其他方法: 使用 Python 在所有驱动器中搜索文件
2021 年 7 月 28 日我有我的 Debian、Raspberry Pi 和程序 Thonny,使用上面的,发现 df 终端命令将我的 1 TB 的 USB 硬盘显示为 /media/pi/DANDER1TB
df
/dev/sdb1 976727036 215780340 760946696 23% /media/pi/DANDER1TB
所以,我只是把它放在搜索程序中并找到了我的 rusty.* 文件,虽然花了 8 秒。
奥派
import fnmatch
import os
# change pattern below to search for anythin on the computer
rootPath = '/media/pi/DANDER1TB'
pattern = 'rusty.*'
for root, dirs, files in os.walk(rootPath):
for filename in fnmatch.filter(files, pattern):
print( os.path.join(root, filename))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.