python saves content to files (text, json, csv)

python saves content to files (text, json, csv)


In the daily life of developers, saving data to a file is one of the most common programming tasks.

Usually, a program needs some input and produces some output. In many cases, we want to persist these results. We may find ourselves saving data to a file for later processing - from the web pages we browse, simple tables, data dumps, reports we use, machine learning and training, or logging while the application is running - we rely on the application to write to the file, not manually.

Python allows us to save all kinds of files without having to use a third-party library.


File open:

When opening a file, you need the file name - a string that can be a relative path or an absolute path. The second parameter is the mode, which determines what you can do with the open file.

my_data_file = open('data.txt', 'w')
  • r  - Default mode, read file( default mode) open the file for reading
  • w  - Open the file and write it. Note that if there is any content in the file, it will be covered; open the file for writing, overwriting the content if the file already exists with data
  • x  - Create a file and ignore it if it already exists; creates a new file, failing if it exists
  • a  - Open the file to write, and attach the new content after the original content; open the file for writing, appending new data at the end of the file's contents if it already exists
  • b  - Write the file in binary format instead of text format; write binary data to files instead of the default text data
  • + - allow reading and writing to a mode

Close a file:


A more common pattern is to use the with pattern:

with open('data.txt', 'w') as my_data_file:
    # TODO: write data to the file
# After leaving the above block of code, the file is closed

To save a text file:

with open('do_re_mi.txt', 'w') as f:
    f.write('Doe, a deer, a female deer\n')
    f.write('Ray, a drop of golden sun\n')

Write multiple lines of data at one time:

with open('browsers.txt', 'w') as f:
    web_browsers = ['Firefox\n', 'Chrome\n', 'Edge\n']
with open('browsers.txt', 'w') as f:
    web_browsers = ['Firefox\n', 'Chrome\n', 'Edge\n']
    f.writelines("%s\n" % line for line in web_browsers)

Write to CSV file:

import csv

weekdays = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']
sales = ['10', '8', '19', '12', '25']

with open('sales.csv', 'w') as csv_file:
    csv_writer = csv.writer(csv_file, delimiter=',')

Write to json file:

import json

my_details = {
    'name': 'John Doe',
    'age': 29

with open('personal.json', 'w') as json_file:
    json.dump(my_details, json_file)


Saving files is useful in many programs we write. To write a file in Python, we first need to open the file and make sure we close it later.

It's better to use the with keyword so that when we write to the file, it will close automatically.

We can use the write() method to put the contents of the string into the file, or use writelines() if there is a text sequence to put into the file.

For CSV and JSON data, we can use the special functions provided by Python to write the data to the file when the file is opened.


Reference: Saving Text, JSON, and CSV to a File in Python

Reference: json

Tags: Python Machine Learning JSON Data Mining csv

Posted by frans-jan on Fri, 14 May 2021 06:19:35 +0930