Write a List to File in Python

There are many ways you can use Python to write a list to a file: write, writelines, and print. Each of them works a bit differently. Print and write take a single string as an argument, and writelines take a list.

There is also the pickle library that will help you to achieve a similar result.

Write

The following code writes will write words from a list and insert them into file one by one. Each of them will be separated by a comma. It’s also a good practice to close the file after operations.

If you want to separate these words with a new line you can insert the new line (\n) character.

If you want your code to be shorter by one line, you can use the join function inside write instead of the for loop.

This code is going to return the same result as before. Each element in separate lines.

Writelines

The difference between the write and writelines functions is that write takes a string as an argument, while writelines takes a list.

You can use writelines in the following way:

Let’s modify the code in a way where we are going to use the for loop to add new lines between words and pass it as an argument to the writelines function.

If you like, you can even use a single line to achieve the goal. It’s not the most elegant way, but it’s definitely possible.

Print

Normally, the print function writes elements to the console. Each of these elements is separated by the newline character.

If you want to write it to the file, you have to redirect the output to a file, instead of the default console. To do it, add a file as a second argument.

The good thing is that new line characters are inserted by default, and that makes the code look cleaner than before.