durgansh taneja
durgansh taneja

Reputation: 3

Python wont read file line by line

fh=open('Spam.mbox',encoding='utf-8')
data=fh.read()
for line in data:
    print(line)

When I execute the above code, python prints out the data one character at a time instead of line by line. Please advise.

Upvotes: 0

Views: 50

Answers (2)

CobyC
CobyC

Reputation: 2447

When reading files use the with statement because then the file will be closed after it has been processed.

Read line by line:

with open("textfile.txt", "r") as f:
    for line in f:
        print(line)

Read all the lines and then loop through the line:

with open("textfile.txt", "r") as f2:
    lines = f2.readlines()
for ln in lines:
    print(ln)

Upvotes: 0

Aleksander Ikleiw
Aleksander Ikleiw

Reputation: 2675

you can do that using the readlines() function.

with open('Spam.mbox',encoding='utf-8') as f:
    data = f.readlines()

With the data variable you can iterate over it and print each line

for i in data:
    print(i)

Upvotes: 1

Related Questions