Computer >> Computer tutorials >  >> Programming >> Python

How to read text file into a list or array with Python?


f = open('my_file.txt', 'r+')
my_file_data = f.read()
f.close()

The above code opens 'my_file.txt' in read mode then stores the data it reads from my_file.txt in my_file_data and closes the file. The read function reads the whole file at once. You can use the following to read the file line by line and store it in a list:

f = open('my_file', 'r+')
lines = [line for line inf.readlines()]
f.close()