How to Create a List from a File in Python?

Estimated read time 2 min read

To create a list from a 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 file named my_file.txt with the following contents:

1,2,3,4
5,6,7,8
9,10,11,12

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

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

print(my_list)

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, splitting each line into a list of values using the split() method, and appending it to the list my_list.

The split() method splits the string into a list of substrings based on the specified delimiter, which in this case is the comma (,).

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

The resulting output will be:

[['1', '2', '3', '4'], ['5', '6', '7', '8'], ['9', '10', '11', '12']]

Note that the values in the resulting list are still strings. If you need to perform arithmetic operations on them, you may need to convert them to integers or floats using the int() or float() functions.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply