Please note, this is a STATIC archive of website www.tutorialspoint.com from 11 May 2019, cach3.com does not collect or store any user information, there is no "phishing" involved.
Tutorialspoint

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

How do I read a text file into a list or array in python?


1 Answer
Manogna
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()
Advertisements

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.