1 Python FILE HANDLING

1. What is File Handling?

File handling means working with files using Python.

In simple words:
👉 Python can create files
👉 Python can read files
👉 Python can write data to files
👉 Python can delete files

Files help us save data permanently.

2. Types of Files

Common file types:

  • Text files.txt

  • CSV files.csv

  • JSON files.json

In this chapter, we use text files.

3. Open a File

Python uses the open() function.

Syntax


 

File Modes

Mode Meaning
"r" Read
"w" Write (overwrite)
"a" Append
"x" Create new file

4. Read a File ("r")

Example


 

5. Read File Line by Line

Example


 

6. Write to a File ("w")

⚠️ This will overwrite the file.

Example


 

7. Append to a File ("a")

Adds text without deleting old data.

Example


 

8. Best Way: Using with Statement

 

Example (Read)


 

Example (Write)


 

9. Read Only One Line

Example


 

10. Read All Lines as List

Example


 

11. Check if File Exists

Example


 

12. Delete a File

Example


 

13. Common Beginner Mistakes

❌ Forgetting to Close File


 

❌ File not closed.

 

❌ Writing in Read Mode


 

❌ Error.

14. Simple Practice Examples

Example 1: Save User Name


 

Example 2: Read Saved Name


 

Example 3: Append Data


 

15. Summary (Python File Handling)

 

📘 Perfect for Beginner eBook

This chapter is ideal for:

  • Python beginner books

  • School & college students

  • Self-learners

If you want next, I can write:

  • File Handling Exercises

  • CSV File Handling

  • JSON File Handling

  • Mini Python Projects

Just tell me 😊

You may also like...