Python provides several built-in functions for creating, reading, writing files. You don’t need a third-party module to work with files.
To access a file for reading or writing, you need the following sequence of operations:
- Opening File
- Reading/Writing File
- Closing File
Opening File
To read or write a file in Python, you need to call built-in open()
function. open()
function returns a file object and it takes two arguments: filename and mode.
Syntax for open()
function is given below.
open(filename, mode="r")
mode argument indicates how the file is accessed. "r"
indicates the file is accessed in read-only mode, "w"
is used for write mode, "a"
is used for append mode.
Python File Opening Modes
File opening modes in Python are listed as follows:
Mode | Description |
---|---|
r | File is opened in read-only mode (default). To open a file in read-only mode, file should exist. |
w | File is opened in write mode. If the file does not exist, a new file is created. If the file exists, it is truncated to zero length and overwritten. |
a | File is opened in append mode. If the file does not exist, a new file is created. If the file exists, new data is appended to the end of the file. Unlike write mode, file is not truncated to zero length in append mode. |
r+ | File is opened in both reading and writing mode. To open a file in r+ mode, file should exist. |
w+ | File is opened in both reading and writing mode. If the file does not exist, a new file is created. If the file exists, it is truncated to zero length and overwritten. |
a+ | File is opened in both reading and writing mode. If the file does not exist, a new file is created. If the file exists, new data is appended at the end of the file. Unlike w+ mode, file is not truncated to zero length in a+ mode. |
Text/Binary Modes
There are 2 types of files: text files and binary files. A text file contains lines of human-readable plain-text strings, whereas a binary file contains unreadable sequence of bytes. Special software is required to process a binary file and interpret its data. .jpg, .mp3, .pdf, .exe files are examples of binary files.
Mode | Description |
---|---|
t | Text Mode (default). Text mode is the default file format mode. If you don’t specify a format, Python opens a file in text mode. |
b | Binary Mode. |
Examples
Opening a File for Writing
To open a text file for writing you need to pass the mode argument as wt. Since text mode is the default mode, you can only pass w.
# opening a text file
my_file = open("demo_file.txt", "wt") # or
my_file = open("demo_file.txt", "w")
# opening a binary file
my_file = open("demo_file.txt", "wb")
Opening a Text File for Reading
Both reading and text modes are default, so you don’t need to specify a mode argument.
my_file = open("demo_file.txt")
To open a file in read-only mode, the file should exist. If demo_file.txt does not exist, Python will give the following error.
FileNotFoundError: [Errno 2] No such file or directory: 'demo_file.txt'
Writing vs Appending
Consider demo_file.txt file has the following contents.
demo_file.txt
This is the first line of the demo file
This is the second line of the demo file
In Append mode, what you write is appended to the end of the file.
my_file = open("demo_file.txt", "a")
my_file.write("This the new line")
my_file.close()
demo_file.txt
This is the first line of the demo file
This is the second line of the demo file
This is the new line
In Write mode, file is truncated to zero length and overwritten.
my_file = open("demo_file.txt", "w")
my_file.write("This the new line")
my_file.close()
demo_file.txt
This is the new line
Closing File
When we finish reading or writing a file, we need to properly close the file.
Closing a file frees up the resources allocated for file access.
Closing a file is also important for not losing your work. Changes you have made in a file may not be written to disk until they are flushed. Python flushes everything on buffer to the file on disk when you close the file.
To close a file you can use a try/finally block. It’s a good idea to close the file in finally block to ensure the file is properly closed even if there is an exception in try block.
try:
my_file=open("demo_file.txt", "a")
my_file.write("This is the new line")
finally:
my_file.close()
For cleaner code, you can use with
statement to close files in Python. After executing with
block, close()
method is called implicity.
with open("demo_file.txt", "a") as my_file:
my_file.write("This is the new line")