Table of Contents
ToggleIn 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 ?
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 5In 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 ?
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 9In 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?
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 ?
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?
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?
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?
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.
Pingback: How To Use Lambda Function In List Comprehension In Python -