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

PythonServer Side ProgrammingProgramming

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

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()]
Updated on 01-Oct-2019 11:41:08