How to Create a List from a Text File in Python?

Estimated read time 1 min read

To create a list from a text file in Python, you can use the open() function to open the file and read its contents. Here’s an example:

Suppose we have a text file named my_file.txt with the following contents:


We can read the contents of the file and create a list of its lines using the following code:

with open('my_file.txt', 'r') as file:
    my_list = [line.strip() for line in file]


In this code, we use the with statement to open the file in read mode ('r'). We then use a list comprehension to iterate over each line in the file, removing any leading or trailing whitespace using the strip() method, and appending it to the list my_list.

Finally, we print the contents of the list using the print() function.

The resulting output will be:

['apple', 'banana', 'cherry']

Note that the strip() method removes leading and trailing whitespace characters, including newline characters (\n) that are added when reading lines from a file.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply