Python | Algorithms | Data Structures | Cyber ​​Security | Networks
38.6K subscribers
779 photos
23 videos
21 files
714 links
This channel is for Programmers, Coders, Software Engineers.

1) Python
2) django
3) python frameworks
4) Data Structures
5) Algorithms
6) DSA

Admin: @Hussein_Sheikho

Ad & Earn money form your channel:
https://telega.io/?r=nikapsOH
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.iss.one/DataScience4
3