Working on projects is funny let alone working on projects that solve a certain complex problem. As you are writing your Python programs there might be scenarios where you want to write data to a file. Here, that is where Python comes in handy, it provides powerful tools and features for working with files, making it a convenient and efficient option for handling file I/O operations in your programs.
In this tutorial, I will be showing you how you can leverage Python’s file I/O capabilities to write data to a file for later use. We will cover things like the write() in-built function, file writing modes, and the with statement.
Python Write to a file using write()
You can use the Python built-in function write() to save data in text to a file, but before we write the data we must open the file in a specific mode(read, write) using the open() function. After we are done performing operations on the file it is good practice to close it because this helps to free up resources tied to the file. To close the file we use the close() function.
Steps to write a file in Python
- Step 1 – Open the file in write mode.
- Step 2 – Write data to file.
- Step 3 – Close the file.
Let us look at our first example of writing to a file.
# Open the file in write mode
file = open("test.txt", "w")
# Write a string to the file
file.write("Hello this is SparkByExample.com")
# Close the file
file.close()
This code opens a file named “test.txt” in write mode using the open() function with mode w. A file object is created and assigned to the variable file.
Next, the string “Hello this is SparkByExample.com” is written to the file using the write() method of the file object.
Finally, the file is closed using the close() method of the file object.
Note: If you try to open a file that does not exist a new one will be created instead
To see if data was written to the “test.txt” file, run this code:
# Open the file in write mode
file = open("test.txt", "r")
# reading the data/contents from the file
data = file.read()
# printing the data
print(data)
In the code snippet, we are opening the “test.txt” file in read mode using the open() function with mode r. A file object is created and assigned to the variable file.
Then, the contents of the file are read using the read() function of the file object and assigned to the variable data.
Finally, we print the contents of the file.
The output will be as follows:
# Output:
Hello this is SparkByExample.com
Writing to a file using the with
statement
Python provides a more convenient way for opening files and that is using the with open() statement. This is convenient because the file is closed automatically, no need to close it manually, this indeed is a timer saver for you. Let us see how you can use the Python with open syntax to write data to a file:
# Open the file in write mode using the with statement
with open("test.txt", "w") as file:
# Write a string to the file
file.write("Hello, this is version 2 of SparkByExample.com!")
This code opens the “test.txt” file in write mode using the open() function with mode w and a with statement. The with statement automatically closes the file after it is used, so there’s no need to manually call the close() function.
Inside the with block, the write() function is used to write a string to the file. In this case, the string “Hello, this is version two of SparkByExample.com!” is written to the file.
After the with block is exited, the file is automatically closed.
For good measure let us read the contents of the file using this code:
# Read the content of the file
with open("test.txt", "r") as file:
data = file.read()
print(data)
This code snippet opens the file “test.txt” in read mode using the with statement, reads the contents of the file using the read() function, and stores the content in the data variable. Finally, it prints the data to the console using the print() function.
The output of the above code will be:
# Output:
Hello, this is version 2 of SparkByExample.com!
File modes in Python
As you are working with files, you must be aware that they are modes that you use when opening these files. In the above Python examples, we have used w for writing a file and r for reading a file as modes. By default, files are opened in read mode.
Here are different file modes in Python:
Mode | Description | Example |
---|---|---|
w | write mode, opens a file for writing, creates a new file if it does not exist | open(“test.txt”, “w”) |
r | read mode, this is the default mode, it opens the file for reading | open(“test.txt”, “r”) |
a | append mode | open(“test.txt”, “a”) |
x | exclusive creation mode opens the file in exclusive creation, the operation fails if the file already exists | open(“test.txt”, “x”) |
b | binary mode, opens the file in binary mode | open(“test.txt”, “b”) |
t | text mode, opens the file in text mode | open(“test.txt”, “t”) |
Handling common file I/O errors
As you are handling files there is a high chance that you might encounter errors. To write to or read data from a file, one needs to have permission, if not then you will encounter an error and if you are trying to open a file that does not exist in read mode you get an error as well. Thanks to Python for its versatility because all these errors can be handled with ease with the help of Python try except statement. I will demonstrate how you can handle a file doesn’t exist error:
# Handing Errors
try:
# open file in read mode
file = open('my_file.txt', 'r')
# read the contents of the file
file_contents = file.read()
# close the file
file.close()
except FileNotFoundError:
print('The file could not be found.')
The try block attempts to open a file called my_file.txt in read mode, read its contents, and then close the file. If the file is not found, the code will raise a FileNotFoundError.
To handle this error, the except block catches the FileNotFoundError exception and prints a custom message to the console indicating that the file could not be found.
The output for the above code snippet is this:
# Output:
The file could not be found.
And the code for handling permission errors will look as follows:
# Handling permission error
try:
# open file in write mode
file = open('test.txt', 'w')
# write data to the file
file.write('Hello, this is SparkByExample.com!')
# close the file
file.close()
except PermissionError:
print('You do not have permission to modify this file.')
In this example, the try block attempts to open the file in write mode, write a string to the file and then close the file. If a PermissionError occurs (for example, if the user does not have the necessary permissions to modify the file), the except block catches the exception and prints a custom error message to the console.
The output for the above example is this:
# Output:
You do not have permission to modify this file.
Conclusion
That concludes this tutorial. You can use the Python built-in function write() to save data in text to a file, but before we write the data we must open the file in a specific mode(read, write) using the open() function. After we are done performing operations on the file it is good practice to close it. Alternatively, use the with open() which will automatically close the file
We hope that you will experiment with each concept you have learned and apply it in your future projects.
Related Article
- How to Measure Elapsed Time in Python?
- Handling Date & Time in Python
- How to get Current Time in Python?
- Using #!/usr/bin/env on the first line of a Python script