Python多文件循环

时间:2018-03-06 07:37:52

标签: python

我刚创建了一个循环来读取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)的内容。

有人可以帮我吗?

1 个答案:

答案 0 :(得分:2)

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

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