File Handling in Python

Last Updated : 14 Jan, 2025
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

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:

ModeDescriptionBehavior
rRead-only mode.Opens the file for reading. File must exist; otherwise, it raises an error.
rbRead-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.
wWrite mode.Opens the file for writing. Creates a new file or truncates the existing file.
wbWrite 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.
aAppend mode.Opens the file for appending data. Creates a new file if it doesn’t exist.
abAppend 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.
xExclusive creation mode.Creates a new file. Raises an error if the file already exists.
xbExclusive 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.

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

  • Versatility : File handling in Python allows us to perform a wide range of operations, such as creating, reading, writing, appending, renaming and deleting files.
  • Flexibility : File handling in Python is highly flexible, as it allows us to work with different file types (e.g. text files, binary files, CSV files , etc.) and to perform different operations on files (e.g. read, write, append, etc.).
  • User – friendly : Python provides a user-friendly interface for file handling, making it easy to create, read and manipulate files.
  • Cross-platform : Python file-handling functions work across different platforms (e.g. Windows, Mac, Linux), allowing for seamless integration and compatibility.

Disadvantages of File Handling in Python

  • Error-prone: File handling operations in Python can be prone to errors, especially if the code is not carefully written or if there are issues with the file system (e.g. file permissions, file locks, etc.).
  • Security risks : File handling in Python can also pose security risks, especially if the program accepts user input that can be used to access or modify sensitive files on the system.
  • Complexity : File handling in Python can be complex, especially when working with more advanced file formats or operations. Careful attention must be paid to the code to ensure that files are handled properly and securely.
  • Performance : File handling operations in Python can be slower than other programming languages, especially when dealing with large files or performing complex operations.

File Handling in Python – FAQs

What is Python file handling?

Python file handling refers to the process of working with files on the filesystem. It involves operations such as reading from files, writing to files, appending data and managing file pointers.

What are the types of files in Python?

In Python, files can broadly be categorized into two types based on their mode of operation:

  • Text Files : These store data in plain text format. Examples include .txt files.
  • Binary Files : These store data in binary format, which is not human-readable. Examples include images, videos and executable files.

What are the 4 file handling functions?

The four primary functions used for file handling in Python are:

  • open() : Opens a file and returns a file object.
  • read() : Reads data from a file.
  • write() : Writes data to a file.
  • close() : Closes the file, releasing its resources.

Why is file handling useful?

File handling is essential for tasks such as data storage, retrieval and manipulation. It allows Python programs to interact with external files, enabling data persistence, configuration management, logging and more complex operations like data analysis and processing.

What is tell() in Python file handling?

In Python file handling, tell() is a method of file objects that returns the current position of the file pointer (cursor) within the file. It returns an integer representing the byte offset from the beginning of the file where the next read or write operation will occur.

Here’s a simple example demonstrating the tell() method:

# Open a file in read mode
file = open('example.txt', 'r')

# Read the first 10 characters
content = file.read(10)
print(content)

# Check the current position of the file pointer
position = file.tell()
print("Current position:", position)

# Close the file
file.close()

In this example:

  • file.read(10) reads the first 10 characters from the file.
  • file.tell() returns the current position of the file pointer after reading.


Next Article
Article Tags :
Practice Tags :

Similar Reads

three90RightbarBannerImg