Best ways to Write to File in Python

onestop_databy:

Python

This short tutorial should teach you in Python how to write a text file in Python which is probably a basic skill needed by anyone analyzing data. Here, we focus on 3 different ways to write files and the advantages and disadvantages of each method.

How to Write a Text File

First of all, assume we have the following list of lists which we want to write the data into a text file assuming some formatting.

my_data = [['City Name', 'Country Name', 'Rating'],
           ['San Diego', 'USA', 'A'],
           ['San Francisco', 'USA', 'A-'],
           ['Tokyo', 'Japan', 'A+'],
           ['Rio de Janeiro', 'Brazil', 'B+']]

We want to write the information a file. In Python, we can write a new file using the open() method, with one of the following parameters:

  • “w”: WRITE to a file. Overwrite file if exist, otherwise, create one.
  • “a”: APPEND to a file. Create a new file if it does not exist, otherwise append to it

Now that you learned about the open() method, we can write a file by calling the method write() and passing a string with the information ending with a line break (“\n”) as shown below:

with open("output.txt", "w") as file_object:
    # skip header
    for sub_list in my_data[1:]:
        city_name, country_name, rating = sub_list
        line = "{} is a city in {} and has rating {}\n".format(city_name, country_name, rating)
        file_object.write(line)

Alternatively, you can also write a file like the following:

file_object = open("output.txt", "w+")
# skip header
for sub_list in my_data[1:]:
    city_name, country_name, rating = sub_list
    line = "{} is a city in {} and has rating {}\n".format(city_name, country_name, rating)
    file_object.write(line)
file_object.close()

The problem with the alternative solution above is that you will need to close the file object. However, on the first solution, it closes the file for you

The information in “output.txt” should look like this

San Diego is a city in USA and has rating A
San Francisco is a city in USA and has rating A-
Tokyo is a city in Japan and has rating A+
Rio de Janeiro is a city in Brazil and has rating B+

Last but not least, I wrote a tutorial on how to read and write CSV files which is another way how to write a file.

More Resources

Here are three of my favorite Python Books in case you want to learn more about it.

Related Posts