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.
my_file = open("NewFile.txt", "w+") my_File.write("Hello World!") my_file.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:
This will show you how to delete and move files too!
To display the contents of the file, just use the following two lines:
my_file = open("NewFile.txt", "r") file_contents == my_file.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 write to a file in Python with modules
Of course, some files are going to contain more complex formatting than others. For example, if you want to write a .Doc file in Python, you’ll come unstuck! Open a Word document in a text editor and you’ll see that Microsoft uses a lot of confusing formatting and annotation to define the layout and add additional information.
This is where modules come in!
First, install the module you want via pip. You can do this by using the following command:
pip install python doc-x
If you are running from a command line in Windows, try:
python –m pip install doc-x
Now in your Python code you can do the following:
import docx my_doc = docx.Document() my_doc.add_paragraph("Hello World!") my_doc.save("D:/NewHelloDoc.docx")
This will write “Hello World!” to a document and then close it! You can also do some other, more complex formatting:
my_doc.add_heading("Header 1", 0) my_doc.add_heading("Header 2", 1) my_doc.add_heading("Header 3", 2) my_doc.add_picture("D:/MyPicture.jpg", width=docx.shared.Inches(5), height=docx.shared.Inches(7))
Regardless of the type of file you want to work with, you’ll almost always find a module that can handle it for you. These are usually free to use and come with documentation you can route through! That’s just another of the amazing things about coding in Python!
And that is how to write to a file in Python! If you’re enjoying learning Python, then why not take your education to the next level? We’ve compiled a list of the best online Python courses where you can find some amazing discounts. Check it out!