File Handling in Python
Python Made Easy - (Article 12) Telugu Explanation
1. Introduction - Why File Handling?
Real-life lo manam data ni save cheyyali ante file lo pedatham (like .txt, .csv, .json).
Python lo kuda, File Handling ane concept use chestam data read & write cheyyadaniki.
Example:
- Notes ni text file lo store cheyyadam
- User input ni save cheyyadam
- Data analysis kosam
.csvfiles read cheyyadam
Python provides built-in functions for all this — open(), read(), write(), close()
2. What is a File?
File ante oka container laanti di - data ni permanent ga store chestundi.
File types rendu rakalu untayi
3. File Operations in Python
Python lo file meeda 4 main steps untayi:
1️⃣ Open the file
2️⃣ Read or Write data
3️⃣ Close the file
Get D Naresh’s stories in your inbox
Join Medium for free to get updates from this writer.
Syntax:
file = open("filename", "mode")
# perform read/write operations
file.close()4. File Opening Modes
5. Reading from a File
file = open("example.txt", "r")
content = file.read()
print(content)
file.close()Explanation:
"r"mode → read onlyread()→ full file content ni read chestundi
Suppose example.txt lo content:
Hello Naresh
Welcome to PythonOutput:
Hello Naresh
Welcome to Python6. Writing to a File
file = open("notes.txt", "w")
file.write("Python is easy to learn!\n")
file.write("File handling is simple!")
file.close()Explanation:
"w"mode → file create chesi overwrite chestundiwrite()→ text add chestundi
File lo content:
Python is easy to learn!
File handling is simple!7. Appending Data to File
file = open("notes.txt", "a")
file.write("\nThis line is newly added!")
file.close()Explanation:
"a"mode → existing content preserve chesi new data add chestundi.
8. Reading Line by Line
Sometimes pedda file lo line by line read cheyyali anukuntam
file = open("example.txt", "r")
for line in file:
print(line.strip()) # strip() removes \n
file.close()Output:
Hello Naresh
Welcome to Python9. Using with Statement (Best Practice)
with statement use chesina file automatic ga close avuthundi,
manual close() avasaram ledu
with open("demo.txt", "w") as f:
f.write("Hello Naresh!\n")
f.write("This file closes automatically.")print("Done!")Explanation:
with → context manager, automatically handles closing.
10. Reading Specific Parts
🔹Read First N Characters:
file = open("example.txt", "r")
print(file.read(5))
file.close()Output (first 5 chars):
Hello🔹 Read Single Line:
file = open("example.txt", "r")
print(file.readline())
file.close()🔹 Read All Lines as List:
file = open("example.txt", "r")
lines = file.readlines()
print(lines)
file.close()Output:
['Hello Naresh\n', 'Welcome to Python\n']11. Deleting a File
Sometimes unnecessary files delete cheyyali.
For that, we use os module
import osif os.path.exists("notes.txt"):
os.remove("notes.txt")
print("File deleted successfully.")
else:
print("File not found.")12. Common File Handling Errors
13. Real-Life Example
# Saving student details to a file
with open("students.txt", "w") as f:
while True:
name = input("Enter student name (or 'stop' to exit): ")
if name.lower() == 'stop':
break
f.write(name + "\n")print("All names saved successfully!")Explanation:
User input ni line by line file lo store chestundi.
14.Key Takeaways
open(filename, mode)→ file ni open cheyyadam'r','w','a'modes most commonread(),write(),readline()→ perform operations- Always
close()or usewith open()for safety - Use
os.remove()to delete files
15. Practice Problems
1️.Create a text file and write your daily routine into it.
2️.Read a .txt file and count how many lines are there.
3️.Append 5 new lines to an existing file.
4️.Check if a file exists before deleting.
Previous & Next
Next Article:👉13. Exception Handling in Python
Previous Article:👉11. Object-Oriented Programming (OOPs)









