File Handling in Python (original) (raw)

Last Updated : 14 Jan, 2025

File handling refers to the process of performing operations on a file such as creating, opening, reading, writing and closing it, through a programming interface. It involves managing the data flow between the program and the file system on the storage device, ensuring that data is handled safely and efficiently.

Opening a File in Python

To open a file we can use open() function, which requires file path and mode as arguments:

Python `

Open the file and read its contents

with open('geeks.txt', 'r') as file:

`

This code opens file named geeks.txt.

File Modes in Python

When opening a file, we must specify the mode we want to which specifies what we want to do with the file. Here’s a table of the different modes available:

**Mode **Description **Behavior
r Read-only mode. Opens the file for reading. File must exist; otherwise, it raises an error.
rb Read-only in binary mode. Opens the file for reading binary data. File must exist; otherwise, it raises an error.
r+ Read and write mode. Opens the file for both reading and writing. File must exist; otherwise, it raises an error.
rb+ Read and write in binary mode. Opens the file for both reading and writing binary data. File must exist; otherwise, it raises an error.
w Write mode. Opens the file for writing. Creates a new file or truncates the existing file.
wb Write in binary mode. Opens the file for writing binary data. Creates a new file or truncates the existing file.
w+ Write and read mode. Opens the file for both writing and reading. Creates a new file or truncates the existing file.
wb+ Write and read in binary mode. Opens the file for both writing and reading binary data. Creates a new file or truncates the existing file.
a Append mode. Opens the file for appending data. Creates a new file if it doesn’t exist.
ab Append in binary mode. Opens the file for appending binary data. Creates a new file if it doesn’t exist.
a+ Append and read mode. Opens the file for appending and reading. Creates a new file if it doesn’t exist.
ab+ Append and read in binary mode. Opens the file for appending and reading binary data. Creates a new file if it doesn’t exist.
x Exclusive creation mode. Creates a new file. Raises an error if the file already exists.
xb Exclusive creation in binary mode. Creates a new binary file. Raises an error if the file already exists.
x+ Exclusive creation with read and write mode. Creates a new file for reading and writing. Raises an error if the file exists.
xb+ Exclusive creation with read and write in binary mode. Creates a new binary file for reading and writing. Raises an error if the file exists.

Table of Content

For this article we are using text file with text:

Hello world
GeeksforGeeks
123 456

Reading a File

Reading a file can be achieved by **file.read() which reads the entire content of the file. After reading the file we can close the file using file.close() which closes the file after reading it, which is necessary to free up system resources.

**Example: Reading a File in Read Mode (r)

Python `

file = open("geeks.txt", "r") content = file.read() print(content) file.close()

`

**Output:

Hello world GeeksforGeeks 123 456

**Reading a File in Binary Mode (rb)

Python `

file = open("geeks.txt", "rb") content = file.read() print(content) file.close()

`

**Output:

b'Hello world\r\nGeeksforGeeks\r\n123 456'

Writing to a File

Writing to a file is done using **file.write()which writes the specified string to the file. If the file exists, its content is erased. If it doesn’t exist, a new file is created.

**Example: Writing to a File in Write Mode (w)

Python `

file = open("geeks.txt", "w") file.write("Hello, World!") file.close()

`

**Writing to a File in Append Mode (a)

It is done using file.write() which adds the specified string to the end of the file without erasing its existing content.

Example: For this example, we will use the Python file created in the previous example.

Python `

Python code to illustrate append() mode

file = open('geek.txt', 'a') file.write("This will add this line") file.close()

`

Closing a File

Closing a file is essential to ensure that all resources used by the file are properly released. file.close() method closes the file and ensures that any changes made to the file are saved.

Python `

file = open("geeks.txt", "r")

Perform file operations

file.close()

`

Using with Statement

with statement is used for resource management. It ensures that file is properly closed after its suite finishes, even if an exception is raised.**with open() as method automatically handles closing the file once the block of code is exited, even if an error occurs. This reduces the risk of file corruption and resource leakage.

Python `

with open("geeks.txt", "r") as file: content = file.read() print(content)

`

**Output:

Hello, World! Appended text.

Handling Exceptions When Closing a File

It’s important to handle exceptions to ensure that files are closed properly, even if an error occurs during file operations.

Python `

try: file = open("geeks.txt", "r") content = file.read() print(content) finally: file.close()

`

**Output:

Hello, World! Appended text.

Advantages of File Handling in Python

Disadvantages of File Handling in Python