📁 Chapter 9: File I/O in Python

Learn how to read, write, append, and manage files in Python


🧠 Main Code

📄 file.py – Reading a File

# 📂 FILE I/O in Python

f = open("file.txt", "r")  # 📖 Opens file.txt in read mode
data = f.read()            # 🧠 Reads the entire file content into a string
print(data)                # 🖨️ Prints the content on screen
f.close()                  # 🔐 Closes the file to free resources

📝 Note: Always remember to close the file unless you're using a with block (we’ll cover that soon!).


✍️ file_write.py – Writing to a File

st = "Hey Prathamesh You are amazing and cool"

f = open("Myfile.txt", "w")  # ✏️ Opens Myfile.txt in write mode (creates file if it doesn't exist)
f.write(st)                  # 💾 Writes the string to the file (⚠️ Overwrites existing content!)
f.close()                    # 🔐 Always close the file

💡 Use Case: Writing logs, saving user data, etc.


📜 more_file_types.py – Reading Line by Line

f = open("file.txt")           # Default mode is "r" (read)

line = f.readline()            # 📥 Reads first line

while line != "":              # 🔁 Loop until end of file
    print(line)                # 🖨️ Print current line
    line = f.readline()        # Move to next line

📝 Tip: This method is useful when reading large files line-by-line to save memory.


file_append.py – Appending to a File

st = "Hey Prathamesh You are amazing and cool"

f = open("Myfile.txt", "a")  # ➕ Opens file in append mode (won't delete existing content)
f.write(st)                  # Adds the string to the end of file
f.close()                    # 🔐 Close after writing

📌 Perfect for: Adding logs, updating data, or journaling programs.