【问题标题】:Not opening a specific text file in Python没有在 Python 中打开特定的文本文件
【发布时间】:2016-02-03 14:57:30
【问题描述】:

我有一个包含一堆文本文件的文件夹。我有以下代码在执行时打开其目录中的所有文本文件,并将它们全部放在一个主文本文件“result.txt”中。

import glob

read_files = glob.glob("*.txt")

with open("result.txt", "wb") as outfile:
    for f in read_files:
        with open(f, "rb") as infile:
            outfile.write(infile.read())

我不想让这个脚本打开“result.txt”。除 result.txt 之外的所有文本文件。我怎样才能做到这一点?我不希望它通过将其内容写入自身来复制 result.txt

【问题讨论】:

    标签: python text file-io


    【解决方案1】:

    使用filter 函数:

    read_files = filter(lambda f : f != 'result.txt', glob.glob('*.txt'))
    

    【讨论】:

    • 这比我的解决方案好多了。
    【解决方案2】:

    嗯,你可以在遍历所有文件时过滤result.txt:

    import glob
    
    read_files = glob.glob("*.txt")
    
    with open("result.txt", "wb") as outfile:
        for f in (file for file in read_files if file != "result.txt"):
            with open(f, "rb") as infile:
                outfile.write(infile.read())
    

    或者,为了防止在read_files 列表的进一步使用中出现错误,您可以在 glob.glob 之后从中删除 "result.txt"

    read_files = glob.glob("*.txt")
    try:
        read_files.remove("result.txt")
    except ValueError: #File result.txt does not exist yet
        pass
    

    【讨论】:

    • 删除它对我来说不是最佳选择,因为文本文件很大并且脚本运行了很多次。
    • 我从不建议删除"result.txt"文件,而是删除read_files列表中的相应字符串。
    【解决方案3】:

    您可以使用continue 跳过文件并开始循环的下一次迭代:

    for f in read_files:
        if f == "result.txt":
            continue
        ...
    

    或者,在开始循环之前过滤文件列表:

    read_files = [f for f in glob.glob("*.txt") if f != "result.txt"]
    

    【讨论】:

    • facepalm 我应该能想到的,呵呵……谢谢!
    猜你喜欢
    • 1970-01-01
    • 2013-05-06
    • 2022-07-20
    • 2012-01-31
    • 1970-01-01
    • 1970-01-01
    • 2012-04-08
    • 2019-01-30
    • 1970-01-01
    相关资源
    最近更新 更多