【问题标题】:Searching through my pc to check if i have a file with a certain name using python? [duplicate]搜索我的电脑以检查我是否有一个使用 python 具有特定名称的文件? [复制]
【发布时间】:2021-04-12 16:34:46
【问题描述】:

文件搜索


如何制作一个程序来检查我的电脑是否有一个具有特定名称的文件,无论文件是什么类型,然后打印是或否。 例如,我会输入一个文件名,然后如果我有它,它就会打印出来。我尝试过类似的事情,但它们对我不起作用。

【问题讨论】:

标签: python


【解决方案1】:

您可以为此使用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的答案。

【讨论】:

  • 我在哪里指定我正在寻找的文件的名称?谢谢你的回答
  • @rocks2260 当您调用该函数时。示例:find('name_of_file.file_extension', 'path/to/folder') 如果您想查看结果,只需将其包装在 print() 语句中即可。
  • 感谢您的帮助,再快一点。说我想在这个 pc 目录中搜索,所以它的整个 pc 我会把“这台电脑”放在不带斜杠的地方。
  • @rocks2260 没有办法一次性搜索整个 PC,您必须单独转到每个磁盘的根目录:'c:\\', 'd:\\',等
  • @rocks2260 就像@Mark Ransom 说的那样,用C:/D:/ 搜索是尽可能低的。
【解决方案2】:

您也可以使用 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
    

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-16
    • 1970-01-01
    • 2016-06-20
    • 1970-01-01
    • 2015-12-01
    • 1970-01-01
    相关资源
    最近更新 更多