Spex3
    

Using with Statements for File Handling in Python πŸ“‚πŸ


    

    

Using with Statements for File Handling in Python
The with statement in Python automatically handles file closing, making it the best practice for working with files.

1️⃣ Why Use with for File Handling?

βœ… Automatically closes files (no need to call close())

βœ… Prevents memory leaks

βœ… Handles exceptions properly

2️⃣ Reading a File with with


with open("example.txt", "r") as file:
content = file.read()
print(content) # File is automatically closed after this block
βœ” The file closes automatically when the with block exits.

3️⃣ Writing to a File with with


with open("example.txt", "w") as file:
file.write("Hello, Python!\n")
file.write("File handling made easy!")
βœ” Overwrites the file if it exists.
βœ” Creates a new file if it doesn’t exist.

4️⃣ Appending to a File with with


with open("example.txt", "a") as file:
file.write("\nAppending new data!")
βœ” Adds content without deleting existing data.

5️⃣ Reading a File Line by Line

with open("example.txt", "r") as file:
for line in file:
print(line.strip()) # Reads and prints each line
βœ” Memory-efficient for large files.

6️⃣ Using with for Binary Files

βœ… Reading a binary file (e.g., an image)


with open("image.jpg", "rb") as file:
data = file.read()
print(data[:10]) # Prints first 10 bytes
βœ… Writing a binary file


with open("copy.jpg", "wb") as file:
file.write(data)
βœ” Essential for handling images, PDFs, and other binary formats.

7️⃣ Summary

Operation Mode Example

Read File "r" with open("file.txt", "r") as file:

Write File (overwrite) "w" with open("file.txt", "w") as file:

Append File "a" with open("file.txt", "a") as file:

Read Binary "rb" with open("image.jpg", "rb") as file:

Write Binary "wb" with open("image.jpg", "wb") as file:


    Date: 2025-03-24 00:00:00.000000