⚡0 XP🔥0

Ch 4 · File Handling - Text Files | फ़ाइल प्रबंधन - टेक्स्ट फ़ाइल

Lesson 4 of 10 ⏱ 3 min read ✎ 1 exercises ❓ 5-question quiz ▶ Runs Python

Types of files, opening modes, file paths, reading and writing text files, the with statement, and file pointer functions seek() and tell().

Types of files#

Text file Binary file CSV file
human-readable characters, lines end with EOL (\n) stores data as bytes (images, pickled objects) text file with comma-separated values

Opening modes#

Mode Meaning
r read (default); error if the file doesn't exist
w write; creates or overwrites
a append at the end
r+ / w+ / a+ read and write
add b binary, e.g. rb, wb

Absolute path starts from the root (C:\data\notes.txt); relative path starts from the current folder.

हिंदी में समझें

'w' मोड पुरानी फ़ाइल की सामग्री मिटाकर नई लिखता है, जबकि 'a' मोड अंत में जोड़ता है। with स्टेटमेंट का प्रयोग करने पर फ़ाइल अपने-आप बंद हो जाती है।

Writing and reading#

▶ Try it YourselfPython
Ctrl + Enter to run

Processing a file line by line#

▶ Try it YourselfPython
Ctrl + Enter to run

seek() and tell()#

f.tell() returns the current position (in bytes); f.seek(offset) moves the file pointer (offset from the beginning by default).

▶ Try it YourselfPython
Ctrl + Enter to run

Exam tips#

  • Common programs: count lines starting with a letter, count words/vowels, copy lines from one file to another.
  • read() returns a string, readlines() returns a list.

Practice Exercises

Write your code, then press Check. Your program is tested automatically.

1

Count lines starting with 'T'

The starter code creates story.txt. Print how many lines start with capital letter T.

Expected output:
2

Quick Quiz

Q1.

Mode that adds data at the end of a file is

Q2.

readlines() returns

Q3.

tell() returns

Q4.

Opening a non-existent file in 'r' mode gives

Q5.

Advantage of 'with open(...)' is