Python 搜索多个硬盘

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")

尝试自己编写代码,然后查看解决方案。
有什么不懂的请追问

另请参阅此问题了解其他方法:search files in all drives using 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))