Code With Python
39K subscribers
841 photos
24 videos
22 files
746 links
This channel delivers clear, practical content for developers, covering Python, Django, Data Structures, Algorithms, and DSA – perfect for learning, coding, and mastering key programming skills.
Admin: @HusseinSheikho || @Hussein_Sheikho
Download Telegram
Topic: Python File Handling — Reading, Writing, and Managing Files (Beginner to Advanced)

---

What is File Handling?

• File handling allows Python programs to read from and write to external files — such as .txt, .csv, .json, etc.

• Python uses built-in functions like open(), read(), and write() to interact with files.

---

Opening a File

file = open("example.txt", "r")  # "r" = read mode
content = file.read()
file.close()


---

Using with Statement (Best Practice)

• Automatically handles file closing:

with open("example.txt", "r") as file:
content = file.read()


---

File Modes

"r" — read (default)
"w" — write (creates or overwrites)
"a" — append (adds to the end)
"x" — create (fails if file exists)
"b" — binary mode
"t" — text mode (default)

---

Writing to Files

with open("output.txt", "w") as file:
file.write("Hello, world!")


Note: "w" overwrites existing content.

---

Appending to Files

with open("output.txt", "a") as file:
file.write("\nNew line added.")


---

Reading Line by Line

with open("example.txt", "r") as file:
for line in file:
print(line.strip())


---

Working with File Paths

• Use os.path or pathlib for platform-independent paths.

from pathlib import Path

file_path = Path("folder") / "file.txt"
with open(file_path, "r") as f:
print(f.read())


---

Advanced Tip: Reading and Writing CSV Files

import csv

with open("data.csv", "w", newline="") as file:
writer = csv.writer(file)
writer.writerow(["name", "age"])
writer.writerow(["Alice", 30])


with open("data.csv", "r") as file:
reader = csv.reader(file)
for row in reader:
print(row)


---

Summary

• Use open() with correct mode to read/write files.

• Prefer with statement to manage files safely.

• Use libraries like csv, json, or pickle for structured data.

• Always handle exceptions like FileNotFoundError for robust file operations.

---

Exercise

• Write a Python program that reads a list of names from names.txt, sorts them alphabetically, and saves the result in sorted_names.txt.

---

#Python #FileHandling #ReadWrite #DataProcessing #ProgrammingTips

https://t.me/DataScience4
3