5 Python Working with CSV & text files
1. What Are Text and CSV Files?
Text File (.txt)
-
Stores plain text
-
Easy to read
-
Used for notes, logs, messages
CSV File (.csv)
-
CSV means Comma Separated Values
-
Stores data in rows and columns
-
Used for tables, Excel data, reports
2. Working with Text Files
2.1 Write to a Text File
Example
2.2 Read a Text File
Example
2.3 Append to a Text File
Example
3. Working with CSV Files
Python has a built-in module called csv.
Import CSV Module
3.1 Write to a CSV File
Example
3.2 Read a CSV File
Example
3.3 Read CSV as Dictionary
Example
3.4 Write CSV Using Dictionary
Example
4. Common Beginner Mistakes
❌ Forgetting newline="" in CSV
👉 Extra blank lines may appear.
✔ Use:
❌ Not Using CSV Module
👉 Works, but not recommended.
5. Simple Practice Examples
Example 1: Save User Data to Text File
Example 2: Save Marks to CSV
Example 3: Read CSV and Calculate Total
6. Text File vs CSV File
| Text File | CSV File |
|---|---|
| Plain text | Table format |
| Human-readable | Excel-friendly |
| Logs, notes | Reports, data |
7. Summary (CSV & Text Files)
✔ Text files store simple text
✔ CSV files store table data
✔ Use with for safety
✔ CSV module makes work easy
✔ Very useful in real projects
📘 Perfect for Beginner eBook
This chapter is ideal for:
-
Python beginner books
-
School & college students
-
Self-learners
If you want next, I can write:
-
JSON File Handling
-
Exception Handling
-
Mini Python Projects
-
Real-world Python Examples
Just tell me 😊
