How to write a list to a file in python

how to write a list to a file in python

In this blog, you will learn how to write a list to a file in Python. You have a list for storing data in memory but what if you want to store data in persistence storage? For that, we have text files, CSV  files, JSON files, and Excel files, or else you can use a database to store data.

How to write a list to a text file in python ?

To write a list to a text file in Python we have majority two methods i.e. using write() method and writelines() method. You have to use a loop to iterate over the data that you want to save into a file using the write function. Here is an example
file_name='data_insertion.txt'
my_data = [1, 2, 3, 4, 5]
with open(file_name, 'w') as file:
    for item in my_data:
        file.write(str(item) + '\n')
Output: Data inside data_insertion.txt file.
1
2
3
4
5
In the above code, the file is opened in write (‘w’) mode using a context manager i.e. with statement. For loop iterates over the data and write function adds data inside the file and the data is saved inside the file. If you want to write whole data at once then we use writelines() function in Python. Let us understand this using an example
my_list = ["Mangesh", "Rahul", "Rohit","Nishil","Mayur","Varun"]

with open("data_insertion.txt", "w") as f:
  f.writelines(my_list)  
Output:
Mangesh Rahul Rohit Nishil Mayur Varun

How to write a 2D list to a text file in python ?

To add 2d list to text file we will use write function in python. Each list inside a list needs to be converted into a string. We have to add a ‘\n’ character after a list to maintain the format of list. 
my_2d_data = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]

file_name='data_insertion.txt'
with open(file_name, 'w') as file:
    for row in my_2d_data:
        file.write(' '.join(map(str, row)) + '\n') 
Output:
1 2 3
4 5 6
7 8 9
In the above code, map function is used to convert the list object to a string object then You are using the join function to add the next line character to the string object. Once both operations are performed write that data to file.

How to write a list to a CSV file in Python?

To write a list into a CSV file in Python you have to use ‘csv’ module. You can do it by following way.
import csv

my_data = [1, 2, 3, 4, 5]
file_name='data_insertion.csv'

with open(file_name, 'w', newline='') as file:
    writer = csv.writer(file)
    for item in my_data:
        writer.writerow([item])
Output:
1
2
3
4
5

How to write a list to a Excel file in Python ?

We have openxyl module for writing data in Excel. We import the workbook class from openxyl module. You create a new workbook called “wb” by creating a Workbook() object. You can use two loops one inside another for getting iterating over the 2 dimensional list. Then insert the value in the Excel workbook by calling the cell() function. The cell() function accepts row, column, and value parameters. 
from openpyxl import Workbook

file_name="data_insertion.xlsx"
wb = Workbook()
ws = wb.active

my_list = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]

for row_index, row_data in enumerate(my_list, start=1):
    for col_index, value in enumerate(row_data, start=1):
        ws.cell(row=row_index, column=col_index, value=value)

wb.save(file_name)
Output
1	2	3
4	5	6
7	8	9

How to write a list to a JSON file in Python?

To save data inside JSON file we need to use JSON module. We open the file in write mode. We use json.dump() function to serialize the data into JSON format and write it to the file. Here is a example.
import json

my_data = [1, 2, 3, 4, 5]
file_name="data_insertion.json"

with open(file_name, 'w') as file:
    json.dump(my_data, file)
Output:
[1, 2, 3, 4, 5]
So, We have learned how to write list to json file python.

How to write a list of integers to a file in Python?

To write a list of integers to text file in python we use the write function. We iterate over the list and convert element to string and add a next line character. Each integer is added in new line.
my_integer_list = [1, 2, 3, 4, 5]
file_name='data_insertion.txt'

with open(file_name, 'w') as file:
    for integer in my_integer_list:
        file.write(str(integer) + '\n')
Output
1
2
3
4
5

How to write a list of strings to a file in Python?

Adding a list of string into a file follows similar process of adding a integers inside a file. We use write function with for loop to add data inside a file in python.
my_string_list = ['J', 'Nisha', "Tan", "S", "KD"]

with open(file_name, 'w') as file:
    for st in my_string_list:
        file.write(str(st) + '\n')

Output:
J
Nisha
Tan
S
KD

How to write a list of tuples to a file in Python ?

To add a list of tuples to a file in Python we have to convert tuples into strings and add new line characters. We will use a for loop to iterate over a list of tuples and write the data into the file.

my_tuple_data = [(1, 'a'), (2, 'b'), (3, 'c')]
file_name='data_insertion.txt'
with open(file_name, 'w') as file:
    for tpl in my_tuple_data:
        file.write(','.join(map(str, tpl)) + '\n')

Output

1,a
2,b
3,c

How to write transpose of list to CSV file Python?

Before writing the data to a CSV file we have to transpose the data.  This line of code “ list(zip(my_2d_data)) ”  does transposition. The ‘ * ’ operator unpacks the 2-dimensional list. The zip function iterates over the unpacked rows and groups together corresponding elements from each row, effectively transposing the list then it is converted to a list.

We use the CSV module’s functions to write data inside a file.

import csv

my_2d_data = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]

file_name='data_insertion.csv'

t_data = list(zip(*my_2d_data))

with open(file_name, 'w', newline='') as file:
    writer = csv.writer(file)
    writer.writerows(t_data)

output

1,4,7
2,5,8
3,6,9

Conclusion

In this blog we Learned how to write a list to a file in python. It is easy to save list to file in python. You can also explore how to Solve object of type datetime is not JSON serializable in python.

1 thought on “How to write a list to a file in python”

  1. Pingback: How To Use Lambda Function In List Comprehension In Python -

Comments are closed.