Skip to content

Python write list to file

  • by

There are multiple ways to write list to file in Python. In Python Write a list to a text file and read it in required a write() and read() method.

Steps to Write List to a File in Python

  • Open file in write mode
  • Write current items from the list into the text file using loop
  • Close the file after completing the write operation

Use a loop:

with open('your_file.txt', 'w') as f:
    for line in lines:
        f.write(f"{line}\n")

For Python <3.6:

with open('your_file.txt', 'w') as f:
    for line in lines:
        f.write("%s\n" % line)

For Python 2, one may also use:

with open('your_file.txt', 'w') as f:
    for line in lines:
        print >> f, line

Python writes a list to file example

Simple example code write() method writes an item from the list to the file along with a newline character.

items = ['Mango', 'Orange', 'Apple', 'Lemon']
file = open('items.txt', 'w')

for i in items:
    file.write(i + "\n")
file.close()

Output:

Python writes a list to file

Using writelines()

The writelines() method writes the items of a list to the file.

items = ['Table ', 'Chair ', 'Mirror ', 'Curtain ', 'Almirah ']
file = open('items.txt','w')
file.writelines(items)
file.close()

Using the Open Statement

This creates a context manager that automatically closes the file object when we don’t need it anymore.

months = ['January', 'February', 'March', 'April']

with open('months.txt', 'w') as output_file:
    for month in months:
        output_file.write(month + '\n')

Using the String Join Method

months = ['January', 'February', 'March', 'April']

output_file = open('months.txt', 'w')
output_file.write('\n'.join(months))
output_file.close()

Using a Python Lambda

months = ['January', 'February', 'March', 'April']
output_file = open('months.txt', 'w')
map(lambda x: output_file.write(x + '\n'), months)
output_file.close()

Do comment if you have any doubts or suggestions on this Python file topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

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