Learn › Class 12 › Computer Science / Informatics Practices › File handling and data structures (stack)
File handling
Example 1: Count lines that start with 'T'
Open one step at a time. Try the next step yourself first.
- Step 1. with open('story.txt', 'r') as f:
Show step 2
count = 0
Show step 3
for line in f: if line.startswith('T'): count += 1
Show step 4
print(count)
Example 2: Save and load a record with pickle
Open one step at a time. Try the next step yourself first.
- Step 1. import pickle
Show step 2
with open('stu.dat', 'wb') as f: pickle.dump({'roll': 1, 'name': 'Asha'}, f)
Show step 3
with open('stu.dat', 'rb') as f: rec = pickle.load(f)
Show step 4
rec['name'] gives 'Asha'.