So far, all the programs we have seen are console-based, meaning we see the output on the computer screen. But what if we want to save our results in a file on the computer or work with a file stored on the computer? In that case, we need to read from or write to a file. Python has some built-in functions that make file handling easy.
Creating a File
In Python, the open()
function is used for any file operation. Let’s see how to create a file:
# This is an example of crating file in python
open("testfile.txt","w")
When you run this program, a text file named testfile.txt
will be created in the same directory.
The first argument of the open()
function is the file name, and the second parameter is the mode, which indicates what operation will be performed with the file. The table below shows the different file handling modes:
Mode | Function |
“r” | Read from the file. It shows an error if the file does not exist. |
“a” | Append to the end of the file. If the file does not exist, it creates a new file. |
“w” | Write to the file. If the file does not exist, it creates a new file. |
“x” | Create a file. It shows an error if the file already exists. |
Note that both “a” and “w” are used for writing to a file; however, “w” overwrites the existing content, whereas “a” appends new information to the existing content.
You can also specify whether a file will be treated as a binary or text file. The table below shows the modes for this:
Mode | Function |
“t” | Read or write the file as text. |
“b” | Read or write the file as binary. |
The default mode is “t”. In the example above, the mode “w” is used; “w” and “wt” carry the same meaning.
Writing to a File
We just learned how to create a file. Now, let’s learn how to write to a file. There are specific methods for writing to a file, but the write()
function is commonly used. Here’s an example:
# This is an example of writing a file in python
f=open("testfile.txt","w")
f.write("This is the first text in the file.")
f.close()
Here, the file named testfile
is opened in write mode, and then the write()
method is used to write to the file.
If you open the testfile.txt
file in the same directory, you will see the text “This is the first text in the file.”
Note that it is essential to close a file using the close()
function after opening it to avoid unexpected errors.
Opening a File
To open a file, the read()
method is used. Let’s look at an example:
# This is an example of reading from a file in python
f=open("testfile.txt","r")
print(f.read())
f.close()
Output:
This is the first text in the file.
We see the previously written text in the console. Note that the “r” mode is used here. If “w” mode is used, the desired result will not be achieved, so it is essential to be cautious about this.