TGViewer
Python Learning Python Learning @python_bds Β· 5.74K subscribers
Post #1177 714
🐍 Python File I/O (Reading & Writing Files) πŸ“

File Input/Output (I/O) allows your Python programs to interact with external files, reading data from them or writing data to them. This is crucial for persistence, logging, and data processing.

πŸ”Ή 1. Opening Files (open())

The open() function is used to open a file. It returns a file object.

Syntax:
file_object = open("filename.txt", "mode")

Common modes:
β€’ "r": Read (default) - file must exist.
β€’ "w": Write - creates a new file or overwrites an existing one.
β€’ "a": Append - creates a new file or adds to the end of an existing one.
β€’ "x": Exclusive creation - creates a new file, fails if it exists.

πŸ”Ή 2. Reading from Files

Once opened in read mode, you can read content:
β€’ .read(): Reads the entire file content as a single string.
β€’ .readline(): Reads one line at a time.
β€’ .readlines(): Reads all lines into a list of strings.

Example:
# Assuming 'data.txt' contains "Line 1\nLine 2\n"
file = open("data.txt", "r")
content = file.read()
print(content)
file.close() # Always close the file!

Output:
Line 1
Line 2

πŸ”Ή 3. Writing to Files

Once opened in write ("w") or append ("a") mode, you can write content:
β€’ .write(string): Writes a string to the file. Remember to add \n for new lines.

Example:
file = open("output.txt", "w")
file.write("Hello from Python!\n")
file.write("This is a new line.")
file.close()

(Creates/overwrites output.txt with the text.)

πŸ”Ή 4. The with Statement (Best Practice!)

The with statement ensures files are automatically closed even if errors occur. This is the recommended way.

Syntax:
with open("filename.txt", "mode") as file_object:
# perform file operations here
# File is automatically closed after this block
Example:python
with open("names.txt", "w") as f:
f.write("Alice\nBob\n")

with open("names.txt", "r") as f:
for line in f:
print(line.strip()) # .strip() removes newline characters

Output:
Alice
Bob

πŸ”Ή 5. File Modes (Binary vs. Text)

β€’ Text mode (default): "r", "w", "a" - handles text encoding/decoding.
β€’ Binary mode: "rb", "wb", "ab" - handles raw bytes, useful for images, executables, etc.

Example (Binary Write):
with open("data.bin", "wb") as f:
f.write(b'\x01\x02\x03') # Writing bytes


🎯 Today's Goal

βœ”οΈ Understand how to open files in different modes
βœ”οΈ Read and write data to files
βœ”οΈ Master the with statement for safe file handling
  • ❀ 4
  • πŸ‘ 1
More from @python_bds
  1. Oct 8, 2026πŸ› This Python Bug Looks Random, But It Isn't Look at this: functions = [] for i in range(…
  2. Oct 6, 2026🐍 Python Performance Optimization Python Performance Optimization: Make Your Code Faster…
  3. Oct 4, 2026Python Set Methods ✍️
  4. Oct 3, 2026Post #1310
  5. Oct 1, 2026🐍 Python Beginner Notes
  6. Sep 30, 2026🧠 return vs print() in Python These are not interchangeable. def add(a, b): print(a + b)…
Threads Profile ViewerView any public Threads profile without an account.Open ThreadLook β†’Writing with AI? Make it sound human.Metric37 rewrites AI drafts so they read naturally. Free AI detector, 1,500 words free.Try Metric37 β†’