Sick Gaming
[Tut] Writing a List to a File in Python - Printable Version

+- Sick Gaming (https://www.sickgaming.net)
+-- Forum: Programming (https://www.sickgaming.net/forum-76.html)
+--- Forum: Python (https://www.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

<div><div id="ez-toc-container" class="ez-toc-v2_0_18 counter-hierarchy counter-decimal ez-toc-light-blue">
<div class="ez-toc-title-container">
<p class="ez-toc-title">Table of Contents</p>
<p><span class="ez-toc-title-toggle"><a class="ez-toc-pull-right ez-toc-btn ez-toc-btn-xs ez-toc-btn-default ez-toc-toggle" style="display: none;"><i class="ez-toc-glyphicon ez-toc-icon-toggle"></i></a></span></div>
<nav>
<ul class="ez-toc-list ez-toc-list-level-1">
<li class="ez-toc-page-1 ez-toc-heading-level-2"><a class="ez-toc-link ez-toc-heading-1" href="https://blog.finxter.com/writing-a-list-to-a-file-in-python/#Method_1-_Using_Read_And_Write" title="Method 1- Using Read And Write">Method 1- Using Read And Write</a></li>
<li class="ez-toc-page-1 ez-toc-heading-level-2"><a class="ez-toc-link ez-toc-heading-2" href="https://blog.finxter.com/writing-a-list-to-a-file-in-python/#Method_2-_Using_Writelines_Method" title="Method 2- Using Writelines() Method">Method 2- Using Writelines() Method</a></li>
<li class="ez-toc-page-1 ez-toc-heading-level-2"><a class="ez-toc-link ez-toc-heading-3" href="https://blog.finxter.com/writing-a-list-to-a-file-in-python/#Method_3-_Using_The_Pickle_Module" title="Method 3- Using The Pickle Module">Method 3- Using The Pickle Module</a></li>
<li class="ez-toc-page-1 ez-toc-heading-level-2"><a class="ez-toc-link ez-toc-heading-4" href="https://blog.finxter.com/writing-a-list-to-a-file-in-python/#Method_4-_Using_The_Json_Module" title="Method 4- Using The Json Module">Method 4- Using The Json Module</a></li>
<li class="ez-toc-page-1 ez-toc-heading-level-2"><a class="ez-toc-link ez-toc-heading-5" href="https://blog.finxter.com/writing-a-list-to-a-file-in-python/#Conclusion" title="Conclusion">Conclusion</a></li>
</ul>
</nav>
</div>
<p><strong>Problem Statement:</strong> How to write a list to a file with Python?</p>
<p>Mostly Python programmers use persistent storage systems like databases or files to store serialized data structures like <a rel="noreferrer noopener" href="https://blog.finxter.com/declare-an-array-python/" target="_blank">arrays</a>, <a rel="noreferrer noopener" href="https://blog.finxter.com/python-lists/" target="_blank">lists</a>, and <a rel="noreferrer noopener" href="https://blog.finxter.com/python-dictionary/" target="_blank">dictionaries</a>. 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:</p>
<h2><strong>Method 1- Using Read And Write</strong></h2>
<p>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> and <code>write()</code> methods, respectively. Suppose we have the following list of strings and we have to store each string in a file using Python: </p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">colors = ["red", "black", "white", "yellow", "blue"]</pre>
<p>To write the list in to file, we have to follow the steps given below:</p>
<ul>
<li>Firstly, open the file in write mode by passing the file path and access mode “<code>w</code>” to the <code>open()</code> function.</li>
<li>Next, we have to use the “<code>for</code>” loop to iterate the list. In each iteration, we will get a list item that we need to write in the file using the <code>write()</code> method.</li>
<li> After iterating through the whole list, we need to ensure that we have closed the file. For that, we use the <code>close()</code> method.</li>
</ul>
<p>Let’s visualize the above demonstration with the help of the following snippet:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># 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()</pre>
<p><strong>Output:</strong></p>
<pre class="wp-block-code"><code>red black white yellow blue</code></pre>
<p><strong>Note:</strong> The ‘<code>\n</code>‘ character is used for a new line at the end of each item in the list.</p>
<p>Let’s have a look at a situation that demonstrates how we can read the list from the file:</p>
<p><strong>Example:</strong></p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># 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)</pre>
<p><strong>Output:</strong></p>
<pre class="wp-block-code"><code>["red", "black", "white", "yellow", "blue"]</code></pre>
<p class="has-base-2-background-color has-background"><strong>Recommended Read: <a href="https://blog.finxter.com/how-to-read-a-file-line-by-line-and-store-into-a-list/" target="_blank" rel="noreferrer noopener">How to Read a File Line-By-Line and Store Into a List?</a></strong></p>
<h2><strong>Method 2- Using Writelines() Method</strong></h2>
<p>While dealing with multiple lines, we have to use the <code>readlines()</code> and <code>writelines()</code> file methods in Python.  Hence we can write the entire list into a file using the <code>writelines()</code> method.</p>
<p><strong>Example:</strong></p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># 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)</pre>
<p><strong>Output:</strong></p>
<pre class="wp-block-code"><code>red black white yellow blue</code></pre>
<p>⦿ The following example shows how to use <code>readlines()</code> to read the entire list from a file in Python:</p>
<p><strong>Example:</strong></p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># 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()]</pre>
<p><strong>Output:</strong></p>
<pre class="wp-block-code"><code>["red", "black", "white", "yellow", "blue"]</code></pre>
<h2><strong>Method 3- Using The Pickle Module</strong></h2>
<p>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> method from the module is used to write the list into a file and it takes the reference of the file and list as its parameters. The method stores the list efficiently as a binary data stream. As it uses a binary stream, the file can even be opened in binary writing mode (<code>wb</code>).  Using the module, we can convert any object like a list or dictionary into a character stream. The character stream has the information to reconstruct the object in the future.</p>
<p><strong>Approach: </strong>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> function checks if the file exists or not and if it exists, it gets truncated. The function creates a new one if the file doesn’t already exist. Further, the <code>dump()</code> method converts the object and writes it into the file.</p>
<p><strong>Example:</strong></p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># 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)</pre>
<p><strong>Output:</strong></p>
<pre class="wp-block-code"><code>Completed the process of writing the list into a binary file ["red", "black", "white", "yellow", "blue"]</code></pre>
<h2><strong>Method 4- Using The Json Module</strong></h2>
<p>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> method. Generally, when we execute a GET request, we will receive a response in JSON format. We can then store the JSON response in a file for any future use.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># 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)</pre>
<p><strong>Output:</strong></p>
<pre class="wp-block-code"><code>Completed the process of writing json data into json file ["red", "black", "white", "yellow", "blue"]</code></pre>
<h2><strong>Conclusion</strong></h2>
<p>That’s all about how to write a list to a file with Python. I hope you found it helpful. Please <strong><a href="https://blog.finxter.com/" target="_blank" rel="noreferrer noopener">stay tuned</a></strong> and <a href="https://blog.finxter.com/subscribe" target="_blank" rel="noreferrer noopener"><strong>subscribe</strong> </a>for more interesting articles. Happy learning!</p>
<p>Recommended: <strong><a href="https://blog.finxter.com/correct-way-to-write-line-to-file-in-python/" target="_blank" rel="noreferrer noopener">Correct Way to Write line To File in Python</a></strong></p>
<p class="has-text-align-center has-base-2-background-color has-background" style="font-size:16px"><strong>Authors: Rashi Agarwal and Shubham Sayon</strong></p>
</div>


https://www.sickgaming.net/blog/2022/04/11/writing-a-list-to-a-file-in-python/