【问题标题】:Python multiple files loopPython多文件循环
【发布时间】:2018-03-06 07:37:51
【问题描述】:

我刚刚创建了一个循环来读取 Python 中多个文件中的每一行,我的代码如下所示:

filenames = ["a.txt","b.txt","c.txt","d.txt"]
for file in filenames:  
lines = [line.rstrip('\n') for line in open(file)]

但是,Python 只返回最后一个文件 (d.txt) 的内容。

谁能帮帮我?

【问题讨论】:

    标签: python


    【解决方案1】:

    问题是lines 在每次迭代中都会被实际文件的内容覆盖。 Rakesh 解决方案是有效的,但我给了你其他方法,因为你试图在 1 行中做到这一点:

    filenames = ["a.txt","b.txt","c.txt", "d.txt"]
    lines = [line.rstrip('\n') for file in filenames for line in open(file)]
    

    【讨论】:

    • 我在这个读取文件循环中有另一个循环,你的代码不允许我使用其他循环。 lines = [line.rstrip('\n') for file in filenames for line in open(file)] for r in range(11): for c in range(5):
    • 您必须将 for 循环放在 [...] 部分中。你不能把它们放在外面。 Here 你对 1 行生成器有更详细的解释。这个循环的版本应该是这样的:[print(r,c,file, line) for r in range(11) for c in range(5) for file in filenames for line in open(file)]
    • Here in the docs 你有更多关于它的信息
    猜你喜欢
    • 2015-10-25
    • 2021-05-29
    • 2020-09-13
    • 1970-01-01
    • 1970-01-01
    • 2011-11-02
    • 2021-10-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多