Applications that need to save data or their current state rely on the ability to persist data. You can do this with files. By writing to and reading from files, you can save information about an application and use it later.
Continuing with the count of the types of files on your desktop from the previous section, you'll start by writing information to a file.
Writing to File in Three Steps
If you map out the process of writing to a file in pseudocode, you might come up with three distinct steps:
- Create or open a file
- Write your data to the file
- Close the file
You'll mirror these steps using Python code to achieve just what you're trying.
First Step
First, you need to open a file in write mode:
file_out = open("output.txt", "w")
In the code snippet above, you're opening a file called output.txt in write mode ("w") and assigning that to the variable file_out.
If there's no file called output.txt in the directory you're running your script from, then it will be created.
Note: If a file called output.txt already exists, all of its content will be instantly deleted if you open it up in write mode, as shown above.
Second Step
After opening the file, you can write data to it using the .write() method on your file_out variable:
file_out.write('This is what you are writing to the file')
Third Step
Finally, you should always close the file after you're done working with it, or you might run into unexpected effects. For example, you might not be able to delete the file on some systems, or you might see an older version of the file content since changes are committed once the file is closed. You can close a file using the .close() method on your file_out variable:
file_out.close()
Using these three steps, you can create or open files from within your Python scripts and write any content to them.
Practice Writing to File
- Edit the desktop file counter script that you built in the previous section to write its output to a file.
- Run the script and confirm that you can read the output in your new file.
- Take a new screenshot or add another file to your desktop, then run the script again.
- Which possible issues can you identify?
In a future lesson, you'll learn how you can improve this.
Summary: Python, Write to File
-
You can use Python to write data to a file to persist the information after your script has finished running. To do this, you need to:
open()a file in write mode ("w").write()data to the file object you created in the previous step.close()the file object when you're done
-
In the example code snippet, you wrote a string to a
.txtfile, but you can also write Python objects to your files. -
When you applied this process to your file counter script, you might have run into some quirks, such as the data not being nicely formatted and getting overwritten each time you ran the script.