0% found this document useful (0 votes)
109 views

File Handling

The document discusses various aspects of file handling in Python including opening, reading, writing, and closing files. Some key points covered include: - To open a file for reading, writing, or appending, the open() function is used along with the file path and mode ('r', 'w', or 'a'). - Methods like read(), readline(), readlines() can be used to read file contents. write() and writelines() write to files. - When opening a file, the mode determines if it is created, overwritten, or appended to. - Additional file methods provide functionality like seeking, telling the position, renaming, deleting and closing files. - Binary files are

Uploaded by

Jatin Vig
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
109 views

File Handling

The document discusses various aspects of file handling in Python including opening, reading, writing, and closing files. Some key points covered include: - To open a file for reading, writing, or appending, the open() function is used along with the file path and mode ('r', 'w', or 'a'). - Methods like read(), readline(), readlines() can be used to read file contents. write() and writelines() write to files. - When opening a file, the mode determines if it is created, overwritten, or appended to. - Additional file methods provide functionality like seeking, telling the position, renaming, deleting and closing files. - Binary files are

Uploaded by

Jatin Vig
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

File Handling

1. To open a file c:\scores.txt for reading, we use


a) infile = open(“c:\scores.txt”, “r”)
b) infile = open(“c:\\scores.txt”, “r”)
c) infile = open(file = “c:\scores.txt”, “r”)
d) infile = open(file = “c:\\scores.txt”, “r”)

2. To open a file c:\scores.txt for writing, we use


a) outfile = open(“c:\scores.txt”, “w”)
b) outfile = open(“c:\\scores.txt”, “w”)
c) outfile = open(file = “c:\scores.txt”, “w”)
d) outfile = open(file = “c:\\scores.txt”, “w”)

3. To open a file c:\scores.txt for appending data, we use


a) outfile = open(“c:\\scores.txt”, “a”)
b) outfile = open(“c:\\scores.txt”, “rw”)
c) outfile = open(file = “c:\scores.txt”, “w”)
d) outfile = open(file = “c:\\scores.txt”, “w”)

4. Which of the following statements are true?


a) When you open a file for reading, if the file does not exist, an error occurs
b) When you open a file for writing, if the file does not exist, a new file is created
c) When you open a file for writing, if the file exists, the existing file is overwritten with the new file
d) All of the mentioned

5. To read two characters from a file object infile, we use


a) infile.read(2)
b) infile.read()
c) infile.readline()
d) infile.readlines()

6. To read the entire remaining contents of the file as a string from a file object infile, we use
a) infile.read(2)
b) infile.read()
c) infile.readline()
d) infile.readlines()

7. What is the output?


f = None
for i in range (5):
with open("data.txt", "w") as f:
if i > 2:
break
print(f.closed)
a) True
b) False
c) None
d) Error

8. To read the next line of the file from a file object infile, we use
a) infile.read(2)
b) infile.read()
c) infile.readline()
d) infile.readlines()
9. To read the remaining lines of the file from a file object infile, we use
a) infile.read(2)
b) infile.read()
c) infile.readline()
d) infile.readlines()

10. The readlines() method returns


a) str
b) a list of lines
c) a list of single characters
d) a list of integers

11. Which is a built-in function to read a line of text from standard input, which by default comes from the
keyboard?
a) input
b) input & scan
c) scan & scanner
d) scanner

12. What is the output of this program?

str = input("Enter your input: ")


print ("Received input is : ", str)

a) Enter your input: Hello Python


Received input is : Hello Python

b) Enter your input: Hello Python


Received input is : Hello

c) Enter your input: Hello Python


Received input is : Python

d) None of the mentioned

13. Which one of the following is not attributes of file


a) closed
b) softspace
c) rename
d) mode

Attribute Description
file.closed Returns true if file is closed, false otherwise.
file.mode Returns access mode with which file was opened.
file.name Returns name of the file.
file.softspace Returns false if space explicitly required with print, true otherwise.

14. What is the use of tell() method in python?


a) tells you the current position within the file
b) tells you the end position within the file
c) tells you the file is opened or not
d) none of the mentioned

15. What is the current syntax of rename() a file?


a) rename(current_file_name, new_file_name)
b) rename(new_file_name, current_file_name,)
c) rename(()(current_file_name, new_file_name))
d) none of the mentioned

16. What is the current syntax of remove() a file?


a) remove(file_name)
b) remove(new_file_name, current_file_name,)
c) remove(() , file_name))
d) none of the mentioned

17. What is the use of seek() method in files?


a) sets the file’s current position at the offset
b) sets the file’s previous position at the offset
c) sets the file’s current position within the file
d) none of the mentioned

18. Which is/are the basic I/O connections in file?


a) Standard Input
b) Standard Output
c) Standard Errors
d) All of the mentioned

19. What is the output of this program?

import sys
print 'Enter your name: ',
name = ''
while True:
c = sys.stdin.read(1)
if c == '\n':
break
name = name + c
print (name)
If entered name is
sanfoundry
a) sanfoundry
b) sanfoundry, sanfoundry
c) San
d) None of the mentioned

20. What is the output of this program?


import sys
sys.stdout.write(' Hello\n')
sys.stdout.write('Python\n')
a) Compilation Error
b) Runtime Error
c) Hello Python
d) Hello
Python

21. Which of the following mode will refer to binary data?


a) r
b) w
c) +
d) b

22. What is the pickling?


a) It is used for object serialization
b) It is used for object deserialization
c) None of the mentioned
d) All of the mentioned

23. What is unpickling?


a) It is used for object serialization
b) It is used for object deserialization
c) None of the mentioned
d) All of the mentioned

24. Correct syntax of file.writelines() is?


a) file.writelines(sequence)
b) fileObject.writelines()
c) fileObject.writelines(sequence)
d) none of the mentioned

25. In file handling, what does this terms means “r, a”?
a) read, append
b) append, read
c) all of the mentioned
d) none of the mentioned

26. What is the use of “w” in file handling?


a) read
b) write
c) append
d) none of the mentioned

27. What is the use of “a” in file handling?


a) read
b) write
c) append
d) none of the the mentioned

28. Which function is used to read all the characters?


a) read()
b) readcharacters()
c) readall()
d) readchar()

29. Which function is used to read single line from file?


a) readline()
b) readlines()
c) readstatement()
d) readfullline()

30. Which function is used to write all the characters?


a) write()
b) writecharacters()
c) writeall()
d) writechar()
31. Which function is used to write a list of strings in a file
a) writeline()
b) writelines()
c) writestatement()
d) writefullline()

32. Which function is used to close a file in python?


a) close()
b) stop()
c) end()
d) closefile()

33. Is it possible to create a text file in python?


a) Yes
b) No
c) Machine dependent
d) All of the mentioned

34. Which of the following is modes of both writing and reading in binary format in file.?
a) wb+ or w+b
b) w
c) wb
d) w+

35. Which of the following is not a valid mode to open a file?


a) ab
b) rw
c) r+
d) w+

36. What is the difference between r+ and w+ modes?


a) no difference
b) in r+ the pointer is initially placed at the beginning of the file and the pointer is at the end for w+
c) in r+ the write mode is counted first and then comes the read mode
d) depends on the operating system

37. How do you close a file object (fp)?


a) close(fp)
b) fclose(fp)
c) fp.close()
d) fp.__close__()

38. How do you get the current position within the file?
a) fp.seek()
b) fp.tell()
c) fp.loc
d) fp.pos

39. How do you rename a file?


a) fp.name = ‘new_name.txt’
b) os.rename(existing_name, new_name)
c) os.rename(fp, new_name)
d) os.set_name(existing_name, new_name)
40. How do you delete a file?
a) del(fp)
b) fp.delete()
c) os.remove(‘file’)
d) os.delete(‘file’)

41. How do you change the file position to a byte value from the start?
a) fp.seek(byte, 0)
b) fp.seek(byte, 1)
c) fp.seek(byte, 2)
d) none of the mentioned

42. What happens if no arguments are passed to the seek function?


a) file position is set to the start of file
b) file position is set to the end of file
c) file position remains unchanged
d) error

43. Which of the following is not true about binary files?


a. Binary files are store in terms of bytes
b. When you open binary file in text editor will show garbage values
c. Binary files represent ASCII value of characters
d. All of the above

44. What is the difference between wb and wb+ mode?


a. wb mode is used to open binary file in write mode and wb+ mode open binary file both for read and
write operation.
b. In wb mode file open in write mode and wb+ in read mode
c. File pointer is at beginning of file in wb mode and in wb+ at the end of file
d. No difference

45. The pickle module in Python is used for:


a. Serializing any Python object structure
b. De-serializing Python object structure
c. Both a and b
d. None of these

46. Which method is used to convert Python objects for writing data in binary file?
a. write()
b. load()
c. store()
d. dump()

47. Which is not the valid mode for binary files?


a. r
b. rb
c. wb
d. wb+

48. Which of the following function is used to read the data in binary file?
a. read()
b. open()
c. dump()
d. load()
49. Suresh wants to open the binary file student.dat in read mode. He writes the following statement but he
does not know the mode. Help him to find the same. F=open(‘student.dat’, ____)
a. r
b. rb
c. w
d. wb
50. This method returns an integer that specifies the current position of the file object.
a. seek()
b. load()
c. position()
d. tell()

51. What is pickling?


a. It is the process to read binary file
b. It is the process to position the file pointer
c. It is a process by which a Python object is converted to a byte stream
d. None of these

52. Mr. Zack Sullivan loves programming. He joined an institute for learning. He is learning python. He
learned all the python concepts like strings, lists, tuple, dictionaries etc. but he wants to learn file handling in
python. He is trying to learn binary file handling. His teacher gave him partial code to write and read data
from employee.dat having structure empno, name, salary. Help Zack to complete the code:

___________________ # statement 1
def addrecords():
fw= _____________ #statement 2
dict={} ch=’y’
while ch==’y’:
eno=int(input(“enter employee number”))
nm= input(“enter employee name”)
sal=int(input(“enter employee salary”))
dict={‘empno’:eno,’name’:nm,’salary’:sal}
____________________ # statement 3
ch=input(“add more record”)
fw.close()

# function to diplay records


def display():
dict={}
fr= _____________ # statement 4
dict=____________ # statement 5
fr.close()
print(“data :”,dict)

Answer the questions based on above case study


1. Help Zack to import the module to perform binary file operation in statement 1.
a. csv
b. random
c. pickle
d. file

2. Which statement is used from the following for statement 2 to open the binary file in write mode?
a. open(“employee.dat”,’w’)
b. open(“employee.dat”,’wb’)
c. open(“employee.dat”,’w+’)
d. open(“employee.dat”,’r’)

3. Which statement is used from the following for statement 3 to write dictionary data created in above code,
namely dict, is written in binary file employee.dat file?
a. pickle.dump(dict,fw)
b. pickle.dump(fw,dict)
c. fw.dump(dict)
d. pickle.store(dict)

4. Which statement is used from the following for statement 4 to open the binary file in read mode?
a. open(“employee.dat”,’r’)
b. open(“employee.dat”,’r+’)
c. open(“employee.dat”,’a’)
d. open(“employee.dat”,’rb’)

5. Complete statement 5 to read data in dictionary namely dict from the opened binary file?
a. dict=pk.read(fr)
b. dict=pickle.load(fr)
c. pickle.load(dict,fr)
d. none of these

53. Now Mr. Zack has given the following code to modify the records of employees from employee.dat used
in above code. He has to increase Rs. 2000 in the salary of those who are getting less than 15000. Mr. Zack
has to find the records and change the salary in place. His teacher gave him partial code. Help him to complete
the code.
import pickle as pk
found=False
emp={}
fin = ___________ #1 statement : open file both in read write mode
# read from file
try:
while true:
pos= _______ #2 store file pointer position before reading record
emp=_______ #3 to read the record in emp dictionary
if emp[‘salary’]<15000:
emp[‘salary’]+=2000
_________ #4 place file pointer at exact location of record
pickle.dump(emp,fin)
found=True
except EOFError:
if found==False:
print(“record not found”)
else:
print(“successfully updated”)
fin.close()

1. In #1 statement open the file in read and write mode. Which statement is used out of the following?
a. open(“employee.dat”,’rb+’)
b. open(“employee.dat”,’r+’)
c. open(“employee.dat”,’a’)
d. open(“employee.dat”,’rb’)

2. Choose the appropriate statement to complete #2 statement to store file pointer position before reading
record.
a. pk.seek(pos)
b. fin.tell()
c. pk.position()
d. pk.tell()

3. Choose the appropriate statement to complete #3 statement to read record in emp dictionary.
a. pk.read(fin)
b. pickle.load(fin,emp)
c. pk.dump(emp)
d. pk.load(fin)

4. Choose the appropriate statement to complete #4 statement to place file pointer at exact location of
record
a. fin.seek(pos)
b. pos=fin.seek()
c. fin.position()
d. none of the above

54. Which of the following file mode opens a file for reading and writing both as well as overwrite the
existing file if the file exists otherwise creates a new file?
a) w
b) wb+
c) wb
d) rwb

55. Which of the following file mode opens a file for append or read a binary file and moves the files pointer
at the end of the file if the file already exist otherwise create a new file?
a) a
b) ab
c) ab+
d) a+

56. Ms. Suman is working on a binary file and wants to write data from a list to a binary file. Consider list
object as l1, binary file suman_list.dat, and file object as f. Which of the following can be the correct
statement for her?
a) f=open(‘sum_list’,’wb’);
pickle.dump(l1,f)

b) f = open(‘sum_list’,’rb’);
l1=pickle.dump(f)

c) f = open(‘sum_list’,’wb’);
pickle.load(l1,f)

d) f = open(‘sum_list’,’rb’);
l1=pickle.load(f)

57. Which option will be correct for reading file for suman from q-56?

58. In which of the file mode existing data will be intact in binary file?
a) ab
b) a
c) w
d) wb

59. Which one of the following is correct statement?


a) import –pickle
b) pickle import
c) import pickle
d) All of the above
60. Every file has its own identity associated with it. Which is known as –
a. icon
b. extension
c. format
d. file type
61. Which of the following is not a known file type?
a. .pdf
b. jpg
c. mp3
d. txp
62. In f=open(“data.txt”, “r”), r refers to __________.
a. File handle
b. File object
c. File Mode
d Buffer
63. EOL stands for
a. End Of Line
b. End Of List
c. End of Lines
d. End Of Location
64. 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
65. 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
66. Which of the following is not a proper file access mode?
a. close
b. read
c. write
d. append
67. 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
68. Which of the following functions flushes the data before closing the file?
a. flush()
b. close()
c. open()
d. fflush()
69. Rohit, a student of class 12th, is learning CSV File Module in Python. During examination, he has been
assigned an incomplete python code (shown below) to create a CSV File 'Student.csv' (content shown
below). Help him in completing the code which creates the desired CSV File.
Contents of the CSV File
1, AKSHAY, XII, A
2, ABHISHEK, XII, A
3, ARVIND, XII, A
4, RAVI, XII, A
5, ASHISH, XII, A

Incomplete Code
import_____ #Statement-1
fh = open(_____, _____, newline='') #Statement-2
stuwriter = csv._____ #Statement-3
data = []
header = ['ROLL_NO', 'NAME', 'CLASS', 'SECTION']
data.append(header)
for i in range(5):
roll_no = int(input("Enter Roll Number : "))
name = input("Enter Name : ")
class = input("Enter Class : ")
section = input("Enter Section : ")
rec = [ ____ ] #Statement-4
data.append(rec)
stuwriter. _____ (data) #Statement-5
fh.close()
1. Identify the suitable code for blank space in line marked as Statement-1.
a. csv file
b. CSV
c. csv
d. Csv

2. Identify the missing code for blank space in line marked as Statement-2?
a. "School.csv","w"
b. "Student.csv","w"
c. "Student.csv","r"
d. "School.csv","r"

3. Choose the function name (with argument) that should be used in the blank space of line marked as
Statement-3
a. reader(fh)
b. reader(MyFile)
c. writer(fh)
d. writer(MyFile)

4. Identify the suitable code for blank space in line marked as Statement-4.
a. 'ROLL_NO', 'NAME', 'CLASS', 'SECTION'
b. ROLL_NO, NAME, CLASS, SECTION
c. 'roll_no', 'name', 'Class', 'section'
d. roll_no, name, Class, section
5. Choose the function name that should be used in the blank space of line marked as Statement-5 to create
the desired CSV File?
a. dump()
b. load()
c. writerows()
d. writerow()

70. When you read csv file using csv.reader() function it returns the values in _______ object.
a. dictionary
b. tuple
c. nested list
d. sets

71. CSV module allows to write multiple rows using ____________ function.
a. writerows( )
b. writerow( )
c. writer( )
d. None of the above

72. Which of the following parameter needs to be added with open function to avoid blank row followed
file each row in CSV file?
a. delimiter
b. newline
c. writer, delimiter
d. file object

73. which is the correct way to import a csv module?


a. import csv
b. from csv import *
c. None of the above
d. Both A & B

74. Observe the following code and fill the blank in statement1

import csv
with _________ as f: #statement1
r = csv.______(f) #statement2
for row in ______: #statement3
print(_____) #statement4

1. Observe the above code and fill the blank in statement 1

a. open("data.csv")
b. f=open("data.csv")
c. Both A & B are Correct
d. Both A & B are incorrect

2. Observe the above code and fill the blank in statement2


a. load
b. read()
c. reader()
d. readlines()

3. Observe the above code and fill the blank in statement3


a. f
b. r
c. r,f
d. None of the above

4. Observe the above code and fill the blank in statement4


a. r
b. row
c. f
d. csv

You might also like