Read a file line by line in Python

Configurare noua (How To)

Situatie

Reading line by line using readlines().
readlines() is used to read all the lines at a single go and then return them as each line a string element in a list. This function can be used for small files, as it reads the whole file content to the memory, then split it into separate lines. We can iterate over the list and strip the newline ‘\n’ character using strip() function.

Solutie

Pasi de urmat

# Python code to
# demonstrate readlines()

L = [“This\n”, “is a\n”, “test\n”]

# writing to file
file1 = open(‘myfile.txt’, ‘w’)
file1.writelines(L)
file1.close()

# Using readlines()
file1 = open(‘myfile.txt’, ‘r’)
Lines = file1.readlines()

count = 0
# Strips the newline character
for line in Lines:
print(“Line{}: {}”.format(count, line.strip()))

Output:

Line1: This
Line2: is a
Line3: test

Tip solutie

Permanent

Voteaza

(3 din 7 persoane apreciaza acest articol)

Despre Autor

Leave A Comment?