Write a List Data to a File in Python: A Beginner Guide – Python Tutorial

By | November 18, 2020

In this tutorial, we will introduce how to write a list data into a file using python, which is very useful as to python beginners.

There are some ways to write a list data into a file, we will introduce one by one.

Way 1: Use python file.writelines() function

file.writelines() allows use to write a list of lines once, we can use this function to write a list data. Here is an example:

data = ['tutorialexample.com', 'tutorial', 'python']

with open('test.txt', 'w') as f:
    f.writelines((data))

Run this code, you will find the content of test.txt is:

tutorialexample.comtutorialpython

From the result we can find: f.writelines() will not add a new line (\n) to each item in list.

In order to make f.writelines() add a new line (\n) to each item in list, we can do as follows:

data = ['tutorialexample.com', 'tutorial', 'python']

with open('test.txt', 'w') as f:
    f.writelines([d+"\n" for d in data])

Then you will get:

tutorialexample.com
tutorial
python

Way 2: Use file.write() function

In order to write a list data to a file, we can write each item in list one by one.

Here is an example:

data = ['tutorialexample.com', 'tutorial', 'python']

with open('test.txt', 'w') as f:
    for d in data:
        f.write(d+"\n")

Run this code, you will get this result:

tutorialexample.com
tutorial
python

Leave a Reply

Your email address will not be published. Required fields are marked *