【发布时间】:2021-04-12 16:34:46
【问题描述】:
文件搜索
如何制作一个程序来检查我的电脑是否有一个具有特定名称的文件,无论文件是什么类型,然后打印是或否。 例如,我会输入一个文件名,然后如果我有它,它就会打印出来。我尝试过类似的事情,但它们对我不起作用。
【问题讨论】:
-
这能回答你的问题吗? Find a file in python
标签: python
文件搜索
如何制作一个程序来检查我的电脑是否有一个具有特定名称的文件,无论文件是什么类型,然后打印是或否。 例如,我会输入一个文件名,然后如果我有它,它就会打印出来。我尝试过类似的事情,但它们对我不起作用。
【问题讨论】:
标签: python
您可以为此使用os 模块。
import os
def find(name, path):
for root, dirs, files in os.walk(path):
if name in files:
return os.path.join(root, name) # or you could print 'found' or something
这将找到第一个匹配项。如果存在则返回文件路径,否则返回None。请注意,它区分大小写。
这取自this的答案。
【讨论】:
find('name_of_file.file_extension', 'path/to/folder') 如果您想查看结果,只需将其包装在 print() 语句中即可。
C:/ 或D:/ 搜索是尽可能低的。
您也可以使用 Pathlib 模块。使用 Pathlib 编写的代码可以在任何操作系统上运行。
#pathlib will work on any OS (linux,windows,macOS)
from pathlib import Path
# define the search Path here '.' means current working directory. you can specify other path like Path('/User/<user_name>')
search_path = Path('.')
# define the file name to be searched here.
file_name = 'test.txt'
#iteratively search glob() will return generator object. It'll be a lot faster.
for file in search_path.glob('**/*'):
if file.name == file_name:
print(f'file found = {file.absolute()}') #print the file path if file is found
break
【讨论】: