0

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?

0

1 Answer 1

2

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)]
Sign up to request clarification or add additional context in comments.

3 Comments

I have another loop in this read file loop to, your code does not allow me to use other loop. lines = [line.rstrip('\n') for file in filenames for line in open(file)] for r in range(11): for c in range(5):
You have to put that for loops inside the [...] section. You can't place them outside. Here you have a more detailed explanation about 1 line generator. Your version for this loop would be something like this: [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 you have even more info about it works

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.