Spex3
    

File Handling in Python: Opening & Closing Files 📂🐍


    

    

Python makes it easy to work with files using the built-in open() function.

1️⃣ Opening a File in Python (open())
To open a file, use:


file = open("example.txt", "r") # "r" means read mode
The open() function takes two main arguments:

🔹 Filename: "example.txt"
🔹 Mode: "r" (read mode)

2️⃣ File Modes in Python
Mode Description
"r" Read mode (default). File must exist.
"w" Write mode. Overwrites file if it exists, creates a new one if not.
"a" Append mode. Adds content without deleting existing data.
"x" Create mode. Creates a new file, but fails if the file exists.
"b" Binary mode. Used for non-text files (e.g., images, PDFs).
"t" Text mode (default). Reads and writes as text.
🔹 Modes can be combined: "wb" (write in binary), "rt" (read in text).

3️⃣ Closing a File (close())
Always close a file after using it to free system resources.


file = open("example.txt", "r")
# Perform file operations...
file.close() # Closes the file
✔ If a file isn’t closed properly, it can cause memory leaks.

4️⃣ Using with Statement (Auto Close)
✅ The best practice is to use with, which automatically closes the file.


with open("example.txt", "r") as file:
content = file.read() # Reads the file content
print(content)
# File is automatically closed after this block
✔ No need to call close() manually!

5️⃣ Checking If a File is Closed
You can check if a file is closed using .closed.


file = open("example.txt", "r")
print(file.closed) # False (File is open)
file.close()
print(file.closed) # True (File is closed)

6️⃣ Summary

Function Description

open("file.txt", "r") Opens a file in read mode

.close() Closes a file manually

with open() as file: Automatically closes the file after use

.closed Checks if a file is closed


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