Sitemap

File Handling in Python

Python Made Easy - (Article 12) Telugu Explanation

Press enter or click to view image in full size

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 .csv files 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

Press enter or click to view image in full size

3. File Operations in Python

Press enter or click to view image in full size

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

Press enter or click to view image in full size

5. Reading from a File

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

Explanation:

  • "r" mode → read only
  • read() → full file content ni read chestundi

Suppose example.txt lo content:

Hello Naresh
Welcome to Python

Output:

Hello Naresh
Welcome to Python

6. Writing to a File

Press enter or click to view image in full size
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 chestundi
  • write() → 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 Python

9. Using with Statement (Best Practice)

Press enter or click to view image in full size

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 os
if os.path.exists("notes.txt"):
os.remove("notes.txt")
print("File deleted successfully.")
else:
print("File not found.")

12. Common File Handling Errors

Press enter or click to view image in full size

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 common
  • read(), write(), readline() → perform operations
  • Always close() or use with 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)