Worksheets › Class 12 › File Handling in Python › Cheat sheet
Class 12 File Handling in Python: cheat sheet
CBSE Computer Science. Text files with open() modes, read, readline, readlines, write, seek and tell; binary files with pickle; and CSV files with reader and writer.
Key ideas
- open(name, mode) gives a file object; the default mode is 'r', and close() (or a with block) saves and frees the file.
- 'w' creates the file or empties it, 'a' writes at the end, 'r' needs the file to exist; + adds reading or writing, and b makes it a binary file.
- read() gives the rest of the file as one string, read(n) the next n characters, readline() one line with its newline, readlines() a list of lines.
- write(s) writes a string and adds no newline; writelines(L) writes each string of a list, also adding none.
- tell() gives the current position of the file pointer; seek(k) moves it to position k, counting from 0.
- pickle.dump(obj, f) stores a Python object in a binary file and pickle.load(f) reads one back; reading past the end raises EOFError.
- csv.writer(f).writerow(row) writes one line of comma-separated fields and writerows() many; csv.reader(f) gives each row as a list of strings.
Remember
| Text modes | 'r' read; 'w' write, emptying it; 'a' append; 'r+' read and write, file must exist |
| More modes | 'w+' write and read, emptying it; 'a+' append and read; 'rb', 'wb', 'ab' for binary files |
| A file of two lines, ab and cd | read() = 'ab\ncd\n' (6 characters); readline() = 'ab\n'; readlines() = ['ab\n', 'cd\n'] |
| seek and tell | after read(4), tell() gives 4; seek(0) goes back to the start |
| Reading every record | call pickle.load(f) in a while True loop inside try; except EOFError ends it |
| CSV | open with newline=''; next(r) skips the header row; int(row[2]) turns text into a number |
Watch out
- Opening a file with 'w' to add to it: it is emptied first; use 'a'.
- Leaving out the newline characters when counting what read() gives.
- Using a value read from a CSV file as a number without int(): it is a string.
- Expecting write() to start a new line by itself.
Worked example
What lines does class.csv hold after this runs? (a) How many lines? (b) Write the last line. import csv f = open('class.csv', 'w', newline='') w = csv.writer(f) w.writerow(['name', 'class', 'marks']) w.writerows([['Arjun', 12, 49], ['Rohan', 12, 98], ['Kabir', 11, 45]]) f.close()
Working: writerows() writes one line per inner list, fields separated by commas: name,class,marks / Arjun,12,49 / Rohan,12,98 / Kabir,11,45
Answer: (a) 4; (b) Kabir,11,45
Practise File Handling in Python
Revise with this page, then practise: every File Handling in Python sheet in the app is new, with an answer key and working.
Coming soon for Android and iPhone.