In this Python tutorial, we will discuss how to write list to file in Python using different examples.
There are five methods to write a list to file in Python, which are shown below:
- Using a for loop and the write() method
- Using the writelines() method
- Using the join() and the write() method
- Using the JSON module
- Using the pickle
How Python Write List to File
One common task is writing a list to a file, which can be useful for storing data that can be read later or for sharing data with other programs. There are several methods for writing a list to a file in Python, including using a for loop, the writelines()
method, json module, etc.
Method-1: Python Write List to File using a for loop and the write() method
In this method, we use a for loop to iterate through each item in the list, and use the write() method to write each item to the file. We also add a newline character ‘\n’ after each item to write each item on a new line.
# create a list of numbers
my_list = [1, 2, 3, 4, 5]
# open a file named "output.txt" in write mode
with open('output.txt', 'w') as f:
# loop through the list and write each item to the file
for item in my_list:
f.write(str(item) + '\n')
The code writes the elements of the list my_list to a file named output.txt, with each element on a new line. It uses the with
statement to open the file in write mode and automatically close it after writing the data.
- The for loop iterates over each element in the list and writes it to the file as a string, followed by a newline character to create a new line for the next element.
Read: Python list methods
Method-2: Python Write List to File using the writelines() method
In this method, we use the writelines() method to write each item in the list to the file.
# create a list of mobile phone brands
mobile = ['samsung', 'redmi', 'oneplus']
# open a file named "f1.txt" in write mode
file = open('f1.txt', 'w')
# loop through the mobile phone list and write each item to the file
for item in mobile:
file.writelines([item])
# close the file
file.close()
The above code creates a list of mobile phone brands and then opens a file named “f1.txt” in write mode. It then loops through the list and writes each item to the file using the writelines() method. Finally, it closes the file.
Read: Python concatenate list
Method-3: Python Write List to File using the join() and the write() method
In this method, we use the join() method to concatenate all the items in the list into a single string, separated by newline characters ‘\n’. We then use the write() method to write this string to the file.
# Define a list containing different types of values
my_list = ["USA", 2, 3, 4, 5]
# Open a file named 'join.txt' in write mode using a context manager
# and write the contents of the list to the file in a specific format
with open('join.txt', 'w') as f:
f.write('\n'.join(map(str, my_list)))
The above code defines a list called my_list containing various data types. It then uses the with a statement to open a new file called ‘join.txt’ in write mode and writes the contents of my_list to the file, with each element on a new line.
Read: How to Reverse a List in Python
Method-4 Python Write List to File using the JSON module
In this method, we use the json module to write the list to a file in JSON format. We use the dump() method to write the list to the file in a JSON-encoded format.
# Import the json module, which provides an easy way to encode and decode JSON data
import json
# Define a list containing different types of values
my_list = ["USA", 2, 3, 4, 5]
# Open a file named 'output.json' in write mode using a context manager
# and use the json.dump() function to write the contents of the list to the file in JSON format
with open('output.json', 'w') as f:
json.dump(my_list, f)
The above code imports the json module, which provides functionality for working with JSON data. It defines a list called my_list containing various data types.
- It then uses the with statement to open a new file called ‘output.json’ in write mode and writes the contents of the list to the file in JSON format using the json.dump() function.
Read: How to find smallest number in a Python list
Method-5: Python Write List to File using the pickle
In this method, we use the pickle module to write the list to a file in a binary format. We use the dump() method to write the list to the file in a binary-encoded format.
# Import the pickle module, which provides an easy way to serialize and deserialize Python objects
import pickle
# Define a list containing different types of values
my_list = ["USA", 2, 3, 4, 5]
# Open a file named 'output.pkl' in write mode using a context manager and binary mode 'wb'
# and use the pickle.dump() function to write the contents of the list to the file in binary format
with open('output.pkl', 'wb') as f:
pickle.dump(my_list, f)
The above code imports the pickle module, It defines a list called my_list containing various data types.
- It then uses the with statement to open a new file called ‘output.pkl’ in write mode with binary mode ‘wb’, and writes the contents of the list to the file in binary format using the pickle.dump() function.
You may also like to read the following Python tutorials.
- How to insert item at end of Python list
- How to get string values from list in Python
- How to get unique values from a list in Python
Conclusion
In this tutorial, we learned how to write python list to file using the different methods:
- Using a for loop and the write() method
- Using the writelines() method
- Using the join() and the write() method
- Using the JSON module
- Using the pickle
Python is one of the most popular languages in the United States of America. I have been working with Python for a long time and I have expertise in working with various libraries on Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… I have experience in working with various clients in countries like United States, Canada, United Kingdom, Australia, New Zealand, etc. Check out my profile.