How To Do File Handling In Python?

Published On: Wed, 29 Nov 2023 Updated On: Wed, 29 Nov 2023

Mastering File Handling in Python

File handling is a fundamental aspect of any programming language, allowing developers to interact with files on disk. In Python, file handling enables reading from and writing to files, making it possible to store and retrieve data persistently. This blog explores the ins and outs of file handling in Python, including opening, closing, manipulating files, understanding different file modes, and handling exceptions during file operations. Let's dive in and uncover the world of file handling in Python.

How to read and write files in Python?

Python provides straightforward methods for reading data from files and writing data to files.

Reading from Files

To read data from a file, Python offers the built-in function open(), followed by the read() method:

Code Example

# Reading from a file
with open('example.txt', 'r') as file:
    content = file.read()
    print(content)

 

Writing to Files

To write data to a file, use the write() method; combined with the open() function in 'write' mode ('w'):

Code Example

# Writing to a file
with open('output.txt', 'w') as file:
    file.write('Hello, this is a sample text.')

 

Opening, Closing, and Manipulating Files

Opening Files

The open() function allows you to specify various file modes for different operations:

  • 'r' - Read mode (default). Opens the file for reading.
  • 'w' - Write mode. Opens the file for writing, overwriting the existing content, or creating a new file if it does not exist.
  • 'a' - Append mode. Opens the file for writing but appends the new content to the existing content instead of overwriting it.
  • 'x' - Exclusive creation mode. Creates a new file but raises an error if the file already exists.
  • 'b' - Binary mode. Opens the file in binary mode, allowing reading and writing binary data.
  • 't' - Text mode (default). Opens the file in text mode, allowing reading and writing text data.
Code Example

# Opening a file in write mode
with open('new_file.txt', 'w') as file:
    file.write('This is a new file.')

 

Closing Files

Python automatically closes files when the with block ends. However, it's a good practice to close files explicitly after using them:

Code Example

# Explicitly closing a file
file = open('data.txt', 'r')
content = file.read()
file.close()

 

Manipulating Files

You can use various file methods to manipulate files, such as seek() to change the file pointer position, tell() to get the current position, and truncate() to resize the file:

Code Example

# Manipulating files
with open('data.txt', 'r+') as file:
    content = file.read()
    file.seek(0)
    file.write('New content.')

 

Different File Modes and File Objects

File modes dictate how the file should be opened and operated. Here are the essential file modes:

  • 'r' - Read mode - Used for reading data from the file.
  • 'w' - Write mode - Used for writing data to the file. Creates a new file if it doesn't exist or overwrites the existing one.
  • 'a' - Append mode - Used for adding data to the end of the file.
  • 'x' - Exclusive creation mode - Used for creating a new file but raises an error if the file already exists.
  • 'b' - Binary mode - Used for reading and writing binary data.
  • 't' - Text mode (default) - Used for reading and writing text data.

The open() function returns file objects and has several useful methods, such as read(), write(), seek(), tell(), and more.

Handling Exceptions During File Operations

File handling operations may raise exceptions if errors occur, such as file not found or permission denied. To handle such exceptions gracefully, use the try-except block:

Code Example

# Handling exceptions during file operations
try:
    with open('data.txt', 'r') as file:
        content = file.read()

except FileNotFoundError:
    print("File not found.")

except PermissionError:
    print("Permission denied.")

except Exception as e:
    print("An error occurred:", str(e))

Conclusion

In Python, file handling is crucial for reading from and writing to files on disk. By mastering file handling techniques, you can efficiently manage data, store information persistently, and create robust applications. From opening files in different modes to handling exceptions gracefully, Python offers a range of powerful tools to make file handling a seamless part of your programming journey. Armed with the knowledge presented in this guide, you can confidently navigate file-handling operations and take your Python projects to new heights of efficiency and functionality.

 

How To Do File Handling In Python?

Reader Comments


Add a Comment