【问题标题】:Python, find specified file in folderPython,在文件夹中找到指定的文件
【发布时间】:2011-08-10 19:17:07
【问题描述】:

这段代码有什么问题?我想在文件夹中找到指定的文件。感谢您的帮助。

import os, fnmatch

def find(root, mask): //Error
    files_list = os.listdir(os.path.abspath(root))
    for filename in fnmatch.filter(files_list, mask):
        yield filename

def test():
    res = find ('D:\\Sample\\', 'hallo.txt') 

test()

错误:

Error: Traceback (most recent call last): def find(root, mask): NoneType

【问题讨论】:

  • os.dir 应该是什么?
  • 那么您是否收到任何错误,或者您的代码有什么问题?
  • @sth: 对不起,我没有写错误代码:-)
  • 实际的错误信息仍然缺失。

标签: python file find


【解决方案1】:

你的函数是generator,它会一一生成文件名。如果您想要所有匹配项的列表,您可以在res 上致电list

list_of_matches = list(res)

您的默认参数root=os.dir 也没有任何意义。也许使用'.'

【讨论】:

  • 如果他只想要第一个,也可能只有一个匹配,使用match = next(find ('D:\\Sample\\', 'hallo.txt'))
【解决方案2】:

测试功能缺少一些缩进

def test ():
    res = find ('D:\\Sample\\', 'hallo.txt')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-04
    • 1970-01-01
    • 2020-11-05
    • 1970-01-01
    • 2015-06-11
    相关资源
    最近更新 更多