133. File I/O with with Statement

Using the with statement for file I/O in Python ensures that files are automatically closed after their usage, even if an error occurs during file operations. This is because with guarantees the execution of the file's __exit__ method, which closes the file, making the code cleaner and more reliable.

Here are some code examples to demonstrate how to use the with statement for file I/O:

1. Basic File Reading with with Statement

Copy

# Using the 'with' statement to open a file and read its contents
with open('example.txt', 'r') as file:
    content = file.read()
    print(content)

In this example:

  • open('example.txt', 'r') opens the file in read mode.

  • The with statement ensures the file is properly closed after reading, even if an exception occurs.


2. File Writing with with Statement

Copy

# Writing to a file using the 'with' statement
with open('output.txt', 'w') as file:
    file.write("This is a line of text.")
    file.write("\nAnother line of text.")

Here:

  • open('output.txt', 'w') opens the file in write mode.

  • If the file exists, it overwrites the content; if it doesn't exist, it creates a new file.

  • The with statement ensures the file is closed after writing.


3. Appending Data to a File with with Statement

Copy

This example:

  • Opens the file in append mode ('a'), meaning new data will be added at the end of the file.

  • The with statement manages the file, ensuring it is properly closed after writing.


4. Reading Multiple Lines from a File

Copy

  • readlines() reads all lines into a list.

  • The with statement ensures proper file closure after reading.


5. Writing a List of Lines to a File

Copy

  • writelines() writes each item in the list to the file.

  • We add newline characters ("\n") explicitly since writelines() doesn't add them automatically.


6. Reading a File in Binary Mode

Copy

  • 'rb' opens the file in binary read mode.

  • Useful for reading non-text files such as images or audio.


7. Writing a File in Binary Mode

Copy

  • 'wb' opens the file in binary write mode.

  • Writes binary data to a file, typically used for non-text files.


8. Handling File Not Found Exception

Copy

  • A try-except block is used to handle exceptions like FileNotFoundError when opening a file that doesn't exist.


9. File I/O with Context Manager for Both Reading and Writing

Copy

  • This example demonstrates how to manage multiple files at once using the with statement for both reading and writing.


10. Using with for File Operations in a Function

Copy

  • The with statement ensures the file is automatically closed when the function finishes execution, even if an exception occurs.


Summary:

  • The with statement is used to ensure that a file is properly opened and closed after its operations are complete.

  • It guarantees that file resources are managed efficiently, preventing file descriptor leaks.

  • You can use it for reading, writing, appending, and handling binary files, and it can manage multiple file operations in a single block.

By using the with statement, you make your file I/O operations cleaner, safer, and more efficient.

Last updated