Append a File to a List in Python

Last time I wrote an article on how to write a list to a file. This time we are going the other way around: How to read data from a file and write it to a list.

The simplest way to append a file to a list is by using the following code:

Let’s see how it works with the following text file.

Let’s print it:

['First line\n', 'Second line\n', 'Third line']

The first two elements end with the newline character (\n).

Let’s use the for loop:

This is what the result looks like:

First line

Second line

Third line

They are separated by the newline character. If you want to get rid of it, you can use the strip function.

Now, there are no newline characters at the end of the file.

First line
Second line
Third line

Append CSV file to a list

If you are using a CSV file, instead of a text file, the code will be slightly more complicated.

This is the CSV file opened in a text editor:

If you try to use the previous code, you are going to get the following result:

['John,Smith,age,24', 'Alex,Miller,age,53', 'Eric,Williams,age,56']

If that’s what you want, then ok, but you may want to create a list of lists.

Now, you have a beautiful list of lists:

['John', 'Smith', 'age', '24']
['Alex', 'Miller', 'age', '53']
['Eric', 'Williams', 'age', '56']