python - How to read a file line-by-line into a list?

ID : 438

viewed : 183

Tags : pythonstringfilereadlinespython





Top 5 Answer for python - How to read a file line-by-line into a list?

vote vote

99

This code will read the entire file into memory and remove all whitespace characters (newlines and spaces) from the end of each line:

with open(filename) as file:     lines = file.readlines()     lines = [line.rstrip() for line in lines] 

If you're working with a large file, then you should instead read and process it line-by-line:

with open(filename) as file:     for line in file:         print(line.rstrip()) 

In Python 3.8 and up you can use a while loop with the walrus operator like so:

with open(filename) as file:     while (line := file.readline().rstrip()):         print(line) 

Depending on what you plan to do with your file and how it was encoded, you may also want to manually set the access mode and character encoding:

with open(filename, 'r', encoding='UTF-8') as file:     while (line := file.readline().rstrip()):         print(line) 
vote vote

87

See Input and Ouput:

with open('filename') as f:     lines = f.readlines() 

or with stripping the newline character:

with open('filename') as f:     lines = [line.rstrip() for line in f] 
vote vote

78

This is more explicit than necessary, but does what you want.

with open("file.txt") as file_in:     lines = []     for line in file_in:         lines.append(line) 
vote vote

67

This will yield an "array" of lines from the file.

lines = tuple(open(filename, 'r')) 

open returns a file which can be iterated over. When you iterate over a file, you get the lines from that file. tuple can take an iterator and instantiate a tuple instance for you from the iterator that you give it. lines is a tuple created from the lines of the file.

vote vote

57

If you want the \n included:

with open(fname) as f:     content = f.readlines() 

If you do not want \n included:

with open(fname) as f:     content = f.read().splitlines() 

Top 3 video Explaining python - How to read a file line-by-line into a list?







Related QUESTION?