# 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)
Learn Flask development and learn to build cool apps with our premium Python course on Udemy.
Subscribe to be the first to know when a new Python course is released.