How to write to a file in Python – Txt, Docx, CSV, and more!



Writing to files is one of the most important things you will learn in any new programming language. This allows you to save user data for future reference, to manipulate large data sets, or to build useful tools like word processors and spreadsheets. Let’s find out how to write to a file in Python!
How to write to a file in Python – .txt files
The simplest way to write to a file in Python, is to create a new text file. This will allow you to store any string to retrieve later.
To do this, you first open the file, then add the content you want, and then close the file to finish.
myFile = open("NewFile.txt", "w+")

myFile.write("Hello World!")

myFile.close()
In this example, we have opened a new file, written the words “Hello World!” and then closed the file.
The “w+” tells Python that we are writing to a new file. If the file already exists, then that file is overwritten. If the file doesn’t already exist, then it will be created.
But what if you want to append (add) to a file that already exists? In this case, you simply swap the “w+” for an “a+”.
You can learn more useful tricks in a previous article:

How to create a file in Python and more!

This will show you how to delete and move files too!
To display the contents of the file, just use the following two lines:
myFile = open("NewFile.txt", "r")

fileContents == myFile.read()
How to write to other types of file
But what if you have another type of file you want to work with, other than a text file? What if you want to create a new spreadsheet file? Or a new Word document?
In many cases, you simply need to learn the formatting used by a particular file-type and then emulate this. For example, CSV files are used to store spreadsheets. The name “CSV” actually refers to the way this formatting works: “Comma-Separated Values.”
In short, each line represents a row in a database and contains a series of values separated by commas. Each comma represents the start of a new column or cell!
You can, therefore, save a bunch of data using the exact same method you used to create your text file, but ensure to insert commas and new-lines in the right place. If you then save the file as “.CSV” then it will open in Excel when you click on it!
The same goes for many other types of file. For example, you could create a HTML file this way by using triangular tags to define headers, bold text, and other basic formatting!
Many developers will create their own formats for storing data specific to their creations. Now you know how to write to a file in Python regardless of the type of file!
Learn more about CSV files in Python here:

How to open CSV files in Python: store and retrieve large data sets

How to write to a file in Python with modules
Of course, some files are going to...

Top