Saving Text, JSON, and CSV to a File in Python
Saving data to a file is one of the most common programming tasks you may come across in your developer life.
Generally, programs take some input and produce some output. There are numerous cases in which we’d want to persist these results. We may find ourselves saving data to a file for later processing – from webpages we browse, simple dumps of tabular data we use for reports, machine learning and training or logging during the application runtime – we rely on applications writing to files rather than doing it manually.
Python allows us to save files of various types without having to use third-party libraries. In this article, we’ll dive into saving the most common file formats in Python.
Opening and Closing a File
Opening a File
The contents of a file can be accessed when it’s opened, and it’s no longer available for reading and writing after it’s been closed.
Opening a file is simple in Python:
my_data_file = open('data.txt', 'w')
When opening a file you’ll need the filename – a string that could be a relative or absolute path. The second argument is the mode, this determines the actions you can do