Spex3
    

Reading and Writing Files in Python 📂🐍


    

    

Python provides simple functions to read, write, and append data to files in both text and binary formats.

1️⃣ File Modes in Python
Mode Description
"r" Read mode (default). Opens a file for reading. File must exist.
"w" Write mode. Creates a file if it doesn’t exist. Overwrites existing content!
"a" Append mode. Adds new content without overwriting existing data.
"x" Create mode. Creates a new file but fails if the file already exists.
"b" Binary mode. Used for non-text files (e.g., images, PDFs).
"t" Text mode (default). Reads and writes as text.
2️⃣ Reading a Text File (read())
✅ Example: Read an entire file


with open("example.txt", "r") as file:
content = file.read() # Reads the entire file
print(content)
✅ Example: Read line by line (readline())


with open("example.txt", "r") as file:
first_line = file.readline() # Reads one line
print(first_line)
✅ Example: Read all lines into a list (readlines())


with open("example.txt", "r") as file:
lines = file.readlines() # Returns a list of lines
print(lines)

3️⃣ Writing to a File (write())
✅ Example: Writing to a file (overwrites existing content)


with open("example.txt", "w") as file:
file.write("Hello, Python!\n") # Overwrites file content
file.write("Welcome to file handling.")
✔ If the file doesn’t exist, Python creates it automatically.

4️⃣ Appending to a File (append mode)

✅ Example: Adding content without overwriting


with open("example.txt", "a") as file:
file.write("\nThis is a new line!")
✔ Useful for logging or maintaining persistent data.

5️⃣ Working with Binary Files (rb, wb, ab)
Binary mode (b) is used for non-text files like images, PDFs, or audio files.

✅ Reading a binary file (e.g., an image)


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


with open("copy.jpg", "wb") as file:
file.write(binary_data) # Saves binary content to a new file

6️⃣ Summary

Operation Text Mode Binary Mode

Read "r" (read(), readline(), readlines()) "rb"

Write (overwrite) "w" (write()) "wb"

Append (add to file) "a" (write()) "ab"


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