Data File Handling Application Based Questions Answers
Data File Handling Application Based Questions Answers
Example:
f=open("data.txt","w")
f.write("Hello\nHow are you?")
f.close()
Data file handling in python class 12 –Application Based questions
Answers:
1. # Creating file with open() function
f=open("city.txt","w")
f.write("My city is very clean city.") f.close()
# Reading contents from city.txt file
f=open("city.txt","r")
dt = f.read() print(dt) f.close()
2. Output:
Explanation:
In line no. 2, f.readline() function reads first line and stores the output string in l but
not printed in the code, then it moves the pointer to next line in the file. In next
statement we have f.readline(18) which reads next 18 characters and place the
cursor at the next position i.e. comma (,) , in next statement f.read(10) reads next
10 characters and stores in ch3 variable and then cursor moves to the next position
and at last f.readline() function print() the entire line.
3. def count_lines():
f = open("friends.txt") cnt =0
for lines in f: cnt+=1
print("no. of lines:",cnt) f.close()
1/6
4. def display_oddLines():
f = open("friends.txt") cnt =0
for lines in f: cnt+=1
if cnt%2!=0: print(lines)
f.close()
5. def cust_data():
name = input("Enter customer name:")
age=int(input("Enter customer age:")) data =
str([name,age])
f = open("customer.txt","w") f.write(data)
f.close()
2/6