Reputation: 171
I just created a loop to read through each line in multiple files in Python and my code looks like this:
filenames = ["a.txt","b.txt","c.txt","d.txt"]
for file in filenames:
lines = [line.rstrip('\n') for line in open(file)]
However, Python only returns the contents of the last file (d.txt).
Can anyone help me here?
Upvotes: 0
Views: 643
Reputation: 685
The problem is that lines
is being overwrite on each iteration with the content of the actual file. Rakesh solution is valid, but I'm giving you other approach, as you are trying to do it in 1 line:
filenames = ["a.txt","b.txt","c.txt", "d.txt"]
lines = [line.rstrip('\n') for file in filenames for line in open(file)]
Upvotes: 2