Python write list to file

Introduction

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...

# Open the file for writing
F = open('list.txt', 'w')

# List of numbers
L = [1, 2, 3, 4, 5]

# Write the numbers one by one
# Note that we had to convert the
# numbers from integers to strings
# Also a new line is appended to
# each string so that only one number
# occupies each line. If you wish, you can
# remove the new line characters and have
# all numbers written on one line
for i in L:
    F.write(str(i) + "\n")

# Close the file
F.close()

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...

# Import the module
import pickle

# List of numbers
L = [1, 2, 3, 4, 5]

# Open the file in write binary mode
with open('list.txt', 'wb') as F:
    # Dump the list to file
    pickle.dump(L, F)

# To import the list back from disk
with open ('list.txt', 'rb') as F:
    L2 = pickle.load(F)

# Print the list and see if it looks the same
print(L2)

# Close the file
F.close()

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...

# Open the file for writing
F = open('list.txt', 'w')

# List of numbers
L = [1, 2, 3, 4, 5]

# Use a list comprehension to convert the 
# numbers to strings then join all strings 
# using a new line
 F.write("\n".join([str(x) for x in L]))

# Close the file
F.close()

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...

# Import the json module
import json

# Open the file for writing
with open('list.txt', 'w') as F:
    # Use the json dumps method to write the list to disk
    F.write(json.dumps(L))

# To load the list back from disk
# Open the file for reading
with open('list.txt', 'r') as F:
    L2 = json.loads(F.read())

# Print the loaded list to see if it looks the same
print(L2)

# Close the file
F.close()

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...

# Open the file for writing
F = open('list.txt', 'w')

# The reason why we used a list comprehension 
# is that we wanted to convert the numbers to 
# strings so that they can be written to disk
F.writelines([str(x) + "\n" for x in L])

# Close the file
F.close()

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...

# Open the file for writing
F = open('list.txt', 'w')

# Print the list to file
print(L, file=F)

# Close the file
F.close()

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...

# Open the file for writing
F = open('list.txt', 'w')

# Write list to disk
F.write(str(L))

# Close the file
F.close()

References

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

Leave a Reply