Example Python script to write list to text file

Table of contents

Save list to file in Python

Saving data structures such as lists to permanent storage for later retrieval is a common practice in computer programming. This technique is commonly referred to as data serialization or marshaling. The goal is to translate data into a format suitable for storage or transmission over network. In today’s code snippets article, we are going to demonstrate how to save a Python list of integers to file using a couple of methods. Let us get started…

One item at a time

We can open a file in write mode and loop through the list one item at a time. When writing to disk files, we have to be very careful about data types and encoding. The write method accepts strings so the numbers in the list should be converted to strings. In this post, we are not going to worry about encoding but if you are curious, you may check the following article. Back to our example…

Pickle object serialization

Pickle, a powerful serialization module in Python can be used to convert the list into a byte stream and save it to disk. This is actually a professional way to do the job specially if the file is not meant to be used by humans (i.e. a computer not an alien of course). Here is an example code…

Python write string to file

We can convert the list to a single string then write it to disk in one shot. The join method (called on a given string) can be used to concatenate a list of strings. As we indicated earlier, we need to convert the numbers to strings. Will use a list comprehension to achieve that. Take a look at the following code snippet…

Python write json to file

JSON is one of the most popular text formats to represent objects and data structures. Since JSON is built in to Python, we can easily use the JSON module to serialize the list to disk. Take a look at the following example…

Python writelines

writelines() can be used to write a sequence of strings to file. The sequence can be a list of strings or even a list comprehension that produces a list of strings as in our example below…

Using print

In Python 3.x, the print function can also be used to write a list to disk. It is as simple as a one liner…

Convert list to string

And finally, we can convert the list into a string and write it once to disk as in the following code snippet…

References

Thanks for visiting. Leave a comment if you have questions.

Tags:,
3 Comments

Add a Comment

Your email address will not be published. Required fields are marked *