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#
Processing a file line by line#
seek() and tell()#
f.tell() returns the current position (in bytes); f.seek(offset) moves the file pointer (offset from the beginning by default).
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.