# Open the file in read mode with open('file.txt', 'r') as file: # Read all the lines of the file into a list lines = file.readlines() # Print the list of lines print(lines)
To read a file line-by-line into a list in Python, you can use the readlines() method of the file object.
Alternatively, you can also use a for loop to iterate over the lines of the file and append them to a list. Here is an example of how to do this:
# Open the file in read mode with open('file.txt', 'r') as file: # Create an empty list to store the lines lines = [] # Iterate over the lines of the file for line in file: # Remove the newline character at the end of the line line = line.strip() # Append the line to the list lines.append(line) # Print the list of lines print(lines)
Python Mega Course: Learn Python in 60 Days, Build 20 Apps
Learn Python on Udemy completely in 60 days or less by building 20 real-world applications from web development to data science.