File Handling
File Handling
Answers:
1. File
2. File Handling
3. I/O Operations
4. Data file
5. Text File
6. open(“data.txt”,”r”)
7. open(“data.txt”,”w”)
8. File handle or File Object
9. close
10. read(15)
11. readline()
12. readlines()
13. write()
14. writelines()
15. append
16. flush()
17. ASCII, UNICODE
18. CSV
19. open()
20. +
1 Every file has its own identity associated with it. Which is known as –
a. icon
b. extension
c. format
d. file type
a. .pdf
b. jpg
c. mp3
d. txp
a. File handle
b. File object
c. File Mode
d Buffer
a. End Of Line
b. End Of List
c. End of Lines
d. End Of Location
5. Which of the following file types allows to store large data files in the computer memory?
a. Text Files
b. Binary Files
c. CSV Files
d. None of these
6. Which of the following file types can be opened with notepad as well as ms excel?
a. Text Files
b. Binary Files
c. CSV Files
d. None of these
a. close
b. read
c. write
d. append
8. To read 4th line from text file, which of the following statement is true?
a. dt = f.readlines();print(dt[3])
b. dt=f.read(4) ;print(dt[3])
c. dt=f.readline(4);print(dt[3])
d. All of these
a. flush()
b. close()
c. open()
d. fflush()
10. Which of the following functions flushes the data before closing the file?
a. flush()
b. close()
c. open()
d. fflush()
data file handling in python class 12 – Short answer questions/ Conceptual Questions
Please refer notes section for the answers on Data file handling in python class 12.
The following section contains few case study based questions for Data file handling in python
class 12.
1. Write a python program to create and read the city.txt file in one go and print the contents on
the output screen.
Answer:
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. Write a function count_lines() to count and display the total number of lines from the
file. Consider above file – friends.txt.
def count_lines():
f = open("friends.txt")
cnt =0
for lines in f:
cnt+=1
print("no. of lines:",cnt)
f.close()
4. Write a function display_oddLines() to display odd number lines from the text file.
Consider above file – friends.txt.
def display_oddLines():
f = open("friends.txt")
cnt =0
for lines in f:
cnt+=1
if cnt%2!=0:
print(lines)
f.close()
5. Write a function cust_data() to ask user to enter their names and age to store data in
customer.txt file.
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()