Python Program - Read a File Line by Line Into a List
https://www.theitroad.com
here's a Python program that reads a file line by line into a list:
# Open the file in read mode with open('filename.txt', 'r') as file: # Read all lines in the file into a list lines = file.readlines() # Print the contents of the list print(lines)
In this program, we first open the file in read mode using the open()
function, which takes the name of the file as its first argument and the mode as the second argument ('r'
for read mode).
Next, we use the readlines()
method to read all lines in the file into a list, which we store in the lines
variable.
Finally, we print the contents of the list using the print()
function.
Note that the with
statement is used to ensure that the file is properly closed after we're done reading it. This is considered good practice to avoid leaving file resources open unnecessarily.