![]() |
|
[Tut] Writing a List to a File in Python - Printable Version +- Sick Gaming (https://sickgaming.net) +-- Forum: Programming (https://sickgaming.net/forum-76.html) +--- Forum: Python (https://sickgaming.net/forum-83.html) +--- Thread: [Tut] Writing a List to a File in Python (/thread-99229.html) |
[Tut] Writing a List to a File in Python - xSicKxBot - 04-17-2022 Writing a List to a File in Python Table of Contents
Problem Statement: How to write a list to a file with Python? Mostly Python programmers use persistent storage systems like databases or files to store serialized data structures like arrays, lists, and dictionaries. It is because databases and files are reusable, i.e. after analyzing the given data, we can store it in the file, and later that data can be read to use in an application. There are many different ways to write a list to the file in Python. Let’s look at some of them: [b]Method 1- Using Read And Write[/b] Python facilitates us with standard methods used to read the data from the file and to write the data to a file. While dealing with single lines, we can use the Code: read()Code: write()Code: colors = ["red", "black", "white", "yellow", "blue"]To write the list in to file, we have to follow the steps given below:
Let’s visualize the above demonstration with the help of the following snippet: Code: # List of colours
colors = ["red", "black", "white", "yellow", "blue"]
# Opening the file in write mode
file = open('colors.txt', 'w')
# Writing the list to the file
for color in colors: file.write(color + '\n')
# Closing the file
file.close()Output: Code: red black white yellow blueNote: The ‘ Code: \nLet’s have a look at a situation that demonstrates how we can read the list from the file: Example: Code: # Empty list that will read from the file
colors = []
# Opening the file in read mode
with open(r'colors.txt', 'r') as file: for color in file: x = color[:-1] colors.append(x)
print(colors)Output: Code: ["red", "black", "white", "yellow", "blue"]Recommended Read: How to Read a File Line-By-Line and Store Into a List? [b]Method 2- Using Writelines() Method[/b] While dealing with multiple lines, we have to use the Code: readlines()Code: writelines()Code: writelines()Example: Code: # List of colours
colors = ["red", "black", "white", "yellow", "blue"]
# Opening the file in write mode
with open('colors.txt', 'w') as file: # Writing the entire list to the file file.writelines("\n" % color for color in colors)Output: Code: red black white yellow blue⦿ The following example shows how to use Code: readlines()Example: Code: # Empty list that will read from the file
colors = []
# Opening the file in read mode
with open(r'colors.txt', 'r') as file: colors = [color.rstrip() for color in file.readlines()]Output: Code: ["red", "black", "white", "yellow", "blue"]Pickle is a module in Python that is used to serialize or de-serialize an object structure. We can use this module to serialize a list for later use in the same file. The Code: dump()Code: wbApproach: To write a list into the file, we have to first import the pickle module at the start of the program. Then we will use the access mode to open the file. The Code: open()Code: dump()Example: Code: # Importing the pickle module
import pickle
# Writing the list to the binary file
def writel(a): # Storing the list in binary file (wb) mode with open('file', 'wb') as fp: pickle.dump(colors, fp) print('Completed the process of writing the list into a binary file')
# Reading the list to memory
def readl(): # Reading the list in binary file (rb) mode with open('sample', 'rb') as fp: n = pickle.load(fp) return n
# List of colors
colors = ["red", "black", "white", "yellow", "blue"]
# Calling the writel method
writel(colors)
color = readl()
# Printing the list
print(color)Output: Code: Completed the process of writing the list into a binary file ["red", "black", "white", "yellow", "blue"]We can use the JSON module to convert the list into a JSON format and then write it into a file using the JSON Code: dump()Code: # Importing the JSON module
import JSON
def writel(a): with open("colors.json", "w") as fp: json.dump(a, fp) print('Completed the process of writing json data into json file')
# Reading the list to memory
def readl(): with open('colors.json', 'rb') as fp: n = json.load(fp) return n
# List of colors
colors = ["red", "black", "white", "yellow", "blue"]
writel(colors)
color = readl()
# Printing the list
print(color)Output: Code: Completed the process of writing json data into json file ["red", "black", "white", "yellow", "blue"]That’s all about how to write a list to a file with Python. I hope you found it helpful. Please stay tuned and subscribefor more interesting articles. Happy learning! Recommended: Correct Way to Write line To File in Python Authors: Rashi Agarwal and Shubham Sayon |