如何让python搜索整个硬盘 [英] How to make python search the entire HDD
问题描述
我正在为我的计算机制作一个简单的 python 搜索程序,我想知道如何让它扫描整个 C 驱动器以搜索文件,而不是该文件与目标文件位于同一文件夹中?这是我目前所拥有的.
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')
推荐答案
如果你有一个根目录来搜索,你可以使用 os.walk
.它将产生目录路径、该目录中的目录和该目录中的文件名的三元组.例如,如果我们有这样的目录结构:
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
那么这段代码:
for path, dirnames, filenames in os.walk('root'):
print((path, dirnames, filenames))
将打印:
('root', ['dir1', 'dir2'], ['file1', 'file2'])
('root/dir1', [], ['file1'])
('root/dir2', ['subdir'], [])
('root/dir2/subdir', [], ['file1', 'file2', 'file3'])
因此,如果您正在寻找 file3
,您只需继续循环,直到您在 filenames
中看到 file3
(in
运算符 在这里是合适的).一旦你看到它,文件的完整路径是 os.path.join(path, 'file3')
,你应该可以用 os.startfile
打开它.
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
.
这篇关于如何让python搜索整个硬盘的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!