问题
I'm making a simple python search program for my computer and I was wondering how I would get it to scan the entire C Drive to search for a file, instead of the file being in the same folder as the target file? This is what I have so far.
import os
print('What song would you like to listen to?')
choice = input().title()
os.startfile(choice + '.mp3')
回答1:
If you have a root directory to search within, you can use os.walk. It will yield triples of directory paths, directories within that directory, and filenames within that directory. For example, if we have this directory structure:
root
├── dir1
│ └── file1
├── dir2
│ └── subdir
│ ├── file1
│ ├── file2
│ └── file3
├── file1
└── file2
Then this code:
for path, dirnames, filenames in os.walk('root'):
print((path, dirnames, filenames))
Will print:
('root', ['dir1', 'dir2'], ['file1', 'file2'])
('root/dir1', [], ['file1'])
('root/dir2', ['subdir'], [])
('root/dir2/subdir', [], ['file1', 'file2', 'file3'])
So if you’re looking for a file3
, you just keep looping until you see a file3
in filenames
(the in operator would be appropriate here). Once you see it, the full path to the file is os.path.join(path, 'file3')
, which you should be able to open with os.startfile
.
回答2:
Use the file and directory operations available in the os module. Visit the following portion of the Python docs for reference:
https://docs.python.org/2/library/os.html#os-file-dir
Note that you can't extract meta data from files using these methods, so you'll have to depend on the player to do that.
Cheers,
-=Cameron
来源:https://stackoverflow.com/questions/27629469/how-to-make-python-search-the-entire-hdd