【问题标题】:Loop through the files in a directory/folder, filter them and then read information from them line by line遍历目录/文件夹中的文件,过滤它们,然后逐行读取它们的信息
【发布时间】:2018-11-29 12:22:10
【问题描述】:

我想循环浏览文件夹中的文件,并从中读取一些数据:

directory = os.fsencode(directory)
    for file in os.listdir(directory):
        file = os.fsdecode(file)
        if file.endswith(".log"):
            with open(file) as f:
                for line in f:
                   extract(line=line))

with open(file) as f: FileNotFoundError: [Errno 2] No such file or 目录:b'access.log'

这很“奇怪”,因为文件存在。

【问题讨论】:

    标签: python python-3.x file


    【解决方案1】:

    您需要添加文件的基本路径。使用os.path.join(directory, file)

    例如:

    directory = os.fsencode(directory)
    for file in os.listdir(directory):
        file = os.fsdecode(file)
        if file.endswith(".log"):
            with open(os.path.join(directory, file)) as f:
                for line in f:
                   extract(line=line))
    

    【讨论】:

    • 我得到一个错误:不能在路径组件中混合字符串和字节
    • 我使用 python 3.7,如果我保留一个未编码的加入目录版本,它可以工作
    猜你喜欢
    • 2020-09-02
    • 1970-01-01
    • 1970-01-01
    • 2013-08-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-10
    • 2020-03-01
    相关资源
    最近更新 更多