我试图编写一个简单的脚本来搜索我的本地驱动器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))
答案 0 :(得分:1)
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")
尝试自己编写代码,然后查看解决方案。
请问你是否有任何理解。
另请参阅此问题以了解其他方法:search files in all drives using Python
答案 1 :(得分:0)
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))