简体   繁体   中英

Python search multiple hard drives

I'm trying to write a simple script that searches my local drive C: and my two external drives E: and F: for all .docx files and write them to a log. I have the search part down right but can only search one hard drive at a time and can not figure out how to write the results to a .log or .txt file. Here is my starting code: which does work with no error

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)

write the result in file like this:

with open("log.txt","wb") as fs:
    result = "whatever result you are getting"
    fs.write(result)

Update:

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

Try to write the code yourself then see the solution.
Please ask if you did not understand anything.

Also see this question for other methods: search files in all drives using Python

July 28, 2021 I have my Debian, Raspberry Pi, program Thonny, using the above and found that the df terminal command showed my 1 terabyte usb hard drive as /media/pi/DANDER1TB

df

/dev/sdb1 976727036 215780340 760946696 23% /media/pi/DANDER1TB

so, I just put that in the search program and found my rusty.* file, although it took 8 seconds.

Opie

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM