Python Questions and Answers - Files - 1: Advertisement
Python Questions and Answers - Files - 1: Advertisement
Python Questions and Answers - Files - 1: Advertisement
This set of Python Multiple Choice Questions & Answers (MCQs) focuses on “files”.
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”)
Answer: b
Explanation: Execute help(open) to get more details.
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”)
Answer: b
Explanation: w is used to indicate that file is to be written to.
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”)
Answer: a
Explanation: a is used to indicate that data is to be appended.
advertisement
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
Answer: d
Explanation: The program will throw an error.
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()
Answer: a
Explanation: Execute in the shell to verify.
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()
Answer: b
Explanation: read function is used to read all the lines in a file.
7. What will be the output of the following Python code?
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
Answer: a
Explanation: The WITH statement when used with open file guarantees that the file
object is closed when the with block exits.
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()
Answer: c
Explanation: Execute in the shell to verify.
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()
Answer: d
Explanation: Execute in the shell to verify.
10. The readlines() method returns ____________
a) str
b) a list of lines
c) a list of single characters
d) a list of integers
Answer: b
Explanation: Every line is stored in a list and returned.
Python Questions and Answers – Files – 2
« Prev
Next »
This set of Python Certification Questions & Answers focuses on “Files”.
1. Which are the two built-in functions to read a line of text from standard input, which by
default comes from the keyboard?
a) Raw_input & Input
b) Input & Scan
c) Scan & Scanner
d) Scanner
Answer: a
Explanation: Python provides two built-in functions to read a line of text from standard
input, which by default comes from the keyboard. These functions are:
raw_input and input
2. What will be the output of the following Python code?
str = raw_input("Enter your input: ");
print "Received input is : ", str
a)
Enter your input: Hello Python
Received input is : Hello Python
advertisement
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
Answer: a
Explanation: The raw_input([prompt]) function reads one line from standard input and
returns it as a string. This would prompt you to enter any string and it would display
same string on the screen. When I typed “Hello Python!”
3. What will be the output of the following Python code?
str = input("Enter your input: ");
print "Received input is : ", str
a)
Enter your input: [x*5 for x in range(2,10,2)]
Received input is : [x*5 for x in range(2,10,2)]
b)
Enter your input: [x*5 for x in range(2,10,2)]
Received input is : [10, 30, 20, 40]
c)
Enter your input: [x*5 for x in range(2,10,2)]
Received input is : [10, 10, 30, 40]
d) None of the mentioned
Answer: a
Explanation: None.
4. Which one of the following is not attributes of file?
a) closed
b) softspace
c) rename
d) mode
Answer: c
Explanation: rename is not the attribute of file rest all are files attributes.
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.
5. 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
Answer: a
Explanation: The tell() method tells you the current position within the file; in other words,
the next read or write will occur at that many bytes from the beginning of the file.
6. 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
Answer: a
Explanation: This is the correct syntax which has shown below.
rename(current_file_name, new_file_name)
7. 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
Answer: a
Explanation: remove(file_name)
8. What will be the output of the following Python code?
fo = open("foo.txt", "rw+")
print "Name of the file: ", fo.name
# Assuming file has following 5 lines
# This is 1st line
# This is 2nd line
# This is 3rd line
# This is 4th line
# This is 5th line
for index in range(5):
line = fo.next()
print "Line No %d - %s" % (index, line)
# Close opened file
fo.close()
a) Compilation Error
b) Syntax Error
c) Displays Output
d) None of the mentioned
Answer: c
Explanation: It displays the output as shown below. The method next() is used when a
file is used as an iterator, typically in a loop, the next() method is called repeatedly. This
method returns the next input line, or raises StopIteration when EOF is hit.
Output:
Name of the file: foo.txt
Line No 0 - This is 1st line
Answer: a
Explanation: Sets the file’s current position at the offset. The method seek() sets the
file’s current position at the offset.
Following is the syntax for seek() method:
fileObject.seek(offset[, whence])
Parameters
offset — This is the position of the read/write pointer within the file.
whence — This is optional and defaults to 0 which means absolute file positioning, other
values are 1 which means seek relative to the current position and 2 means seek
relative to the file’s end.
10. What is the use of truncate() method in file?
a) truncates the file size
b) deletes the content of the file
c) deletes the file size
d) none of the mentioned
Answer: a
Explanation: The method truncate() truncates the file size. Following is the syntax for
truncate() method:
fileObject.truncate( [ size ])
Parameters
size — If this optional argument is present, the file is truncated to (at most) that size.
Answer: d
Explanation: Standard input, standard output and standard error. Standard input is the
data that goes to the program. The standard input comes from a keyboard. Standard
output is where we print our data with the print keyword. Unless redirected, it is the
terminal console. The standard error is a stream where programs write their error
messages. It is usually the text terminal.
2. What will be the output of the following Python code? (If entered name is sanfoundry)
import sys
print 'Enter your name: ',
name = ''
while True:
c = sys.stdin.read(1)
if c == '\n':
break
name = name + c
print 'Your name is:', name
a) sanfoundry
b) sanfoundry, sanfoundry
c) San
d) None of the mentioned
Answer: a
Explanation: In order to work with standard I/O streams, we must import the sys module.
The read() method reads one character from the standard input. In our example we get a
prompt saying “Enter your name”. We enter our name and press enter. The enter key
generates the new line character: \n.
Output:
Enter your name: sanfoundry
Your name is: sanfoundry
advertisement
3. What will be the output of the following Python code?
import sys
sys.stdout.write(' Hello\n')
sys.stdout.write('Python\n')
a) Compilation Error
b) Runtime Error
c) Hello Python
d)
Hello
Python
Answer: d
Explanation: None
Output:
Hello
Python
4. Which of the following mode will refer to binary data?
a) r
b) w
c) +
d) b
Answer:d
Explanation: Mode Meaning is as explained below:
r Reading
w Writing
a Appending
b Binary data
+ Updating.
5. 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
Answer: a
Explanation: Pickle is the standard mechanism for object serialization. Pickle uses a
simple stack-based virtual machine that records the instructions used to reconstruct the
object. This makes pickle vulnerable to security risks by malformed or maliciously
constructed data, that may cause the deserializer to import arbitrary modules and
instantiate any object.
6. 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
Answer: b
Explanation: We have been working with simple textual data. What if we are working
with objects rather than simple text? For such situations, we can use the pickle module.
This module serializes Python objects. The Python objects are converted into byte
streams and written to text files. This process is called pickling. The inverse operation,
reading from a file and reconstructing objects is called deserializing or unpickling.
7. What is the correct syntax of open() function?
a) file = open(file_name [, access_mode][, buffering])
b) file object = open(file_name [, access_mode][, buffering])
c) file object = open(file_name)
d) none of the mentioned
Answer: b
Explanation: Open() function correct syntax with the parameter details as shown below:
file object = open(file_name [, access_mode][, buffering])
Here is parameters’ detail:
file_name: The file_name argument is a string value that contains the name of the file
that you want to access.
access_mode: The access_mode determines the mode in which the file has to be
opened, i.e., read, write, append, etc. A complete list of possible values is given below in
the table. This is optional parameter and the default file access mode is read (r).
buffering: If the buffering value is set to 0, no buffering will take place. If the buffering
value is 1, line buffering will be performed while accessing a file. If you specify the
buffering value as an integer greater than 1, then buffering action will be performed with
the indicated buffer size. If negative, the buffer size is the system default(default
behavior).
8. What will be the output of the following Python code?
fo = open("foo.txt", "wb")
print "Name of the file: ", fo.name
fo.flush()
fo.close()
a) Compilation Error
b) Runtime Error
c) No Output
d) Flushes the file when closing them
Answer: d
Explanation: The method flush() flushes the internal buffer. Python automatically flushes
the files when closing them. But you may want to flush the data before closing any file.
9. Correct syntax of file.writelines() is?
a) file.writelines(sequence)
b) fileObject.writelines()
c) fileObject.writelines(sequence)
d) none of the mentioned
Answer: c
Explanation: The method writelines() writes a sequence of strings to the file. The
sequence can be any iterable object producing strings, typically a list of strings. There is
no return value.
Syntax
Following is the syntax for writelines() method:
fileObject.writelines( sequence ).
10. Correct syntax of file.readlines() is?
a) fileObject.readlines( sizehint );
b) fileObject.readlines();
c) fileObject.readlines(sequence)
d) none of the mentioned
Answer: a
Explanation: The method readlines() reads until EOF using readline() and returns a list
containing the lines. If the optional sizehint argument is present, instead of reading up to
EOF, whole lines totalling approximately sizehint bytes (possibly after rounding up to an
internal buffer size) are read.
Syntax
Following is the syntax for readlines() method:
fileObject.readlines( sizehint );
Parameters
sizehint — This is the number of bytes to be read from the file.
Answer: a
Explanation: r- reading, a-appending.
2. What is the use of “w” in file handling?
a) Read
b) Write
c) Append
d) None of the mentioned
Answer: b
Explanation: This opens the file for writing. It will create the file if it doesn’t exist, and if it
does, it will overwrite it.
fh = open(“filename_here”, “w”).
3. What is the use of “a” in file handling?
a) Read
b) Write
c) Append
d) None of the mentioned
Answer: c
Explanation: This opens the fhe file in appending mode. That means, it will be open for
writing and everything will be written to the end of the file.
fh =open(“filename_here”, “a”).
advertisement
4. Which function is used to read all the characters?
a) Read()
b) Readcharacters()
c) Readall()
d) Readchar()
Answer: a
Explanation: The read function reads all characters fh = open(“filename”, “r”)
content = fh.read().
5. Which function is used to read single line from file?
a) Readline()
b) Readlines()
c) Readstatement()
d) Readfullline()
Answer: b
Explanation: The readline function reads a single line from the file fh = open(“filename”,
“r”)
content = fh.readline().
6. Which function is used to write all the characters?
a) write()
b) writecharacters()
c) writeall()
d) writechar()
Answer: a
Explanation: To write a fixed sequence of characters to a file
fh = open(“hello.txt”,”w”)
write(“Hello World”).
7. Which function is used to write a list of string in a file?
a) writeline()
b) writelines()
c) writestatement()
d) writefullline()
Answer: a
Explanation: With the writeline function you can write a list of strings to a file
fh = open(“hello.txt”, “w”)
lines_of_text = [“a line of text”, “another line of text”, “a third line”]
fh.writelines(lines_of_text).
8. Which function is used to close a file in python?
a) Close()
b) Stop()
c) End()
d) Closefile()
Answer: a
Explanation: f.close()to close it and free up any system resources taken up by the open
file.
9. Is it possible to create a text file in python?
a) Yes
b) No
c) Machine dependent
d) All of the mentioned
Answer: a
Explanation: Yes we can create a file in python. Creation of file is as shown below.
file = open(“newfile.txt”, “w”)
file.write(“hello world in the new file\n”)
file.write(“and another line\n”)
file.close().
10. Which of the following are the modes of both writing and reading in binary format in
file?
a) wb+
b) w
c) wb
d) w+
Answer: a
Explanation: Here is the description below
“w” Opens a file for writing only. Overwrites the file if the file exists. If the file does not
exist, creates a new file for writing.
“wb” Opens a file for writing only in binary format. Overwrites the file if the file exists. If
the file does not exist, creates a new file for writing.
“w+” Opens a file for both writing and reading. Overwrites the existing file if the file
exists. If the file does not exist, creates a new file for reading and writing.
“wb+” Opens a file for both writing and reading in binary format. Overwrites the existing
file if the file exists. If the file does not exist, creates a new file for reading and writing.
This set of Python written test Questions & Answers focuses on “Files”.
1. Which of the following is not a valid mode to open a file?
a) ab
b) rw
c) r+
d) w+
Answer: b
Explanation: Use r+, w+ or a+ to perform both read and write operations using a single
file object.
2. 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 w+ the pointer is initially placed at the beginning of the file and the pointer is at the
end for r+
d) depends on the operating system
Answer: b
Explanation: none.
3. How do you get the name of a file from a file object (fp)?
a) fp.name
b) fp.file(name)
c) self.__name__(fp)
d) fp.__name__()
Answer: a
Explanation: name is an attribute of the file object.
advertisement
4. Which of the following is not a valid attribute of a file object (fp)?
a) fp.name
b) fp.closed
c) fp.mode
d) fp.size
Answer: d
Explanation: fp.size has not been implemented.
5. How do you close a file object (fp)?
a) close(fp)
b) fclose(fp)
c) fp.close()
d) fp.__close__()
Answer: c
Explanation: close() is a method of the file object.
6. How do you get the current position within the file?
a) fp.seek()
b) fp.tell()
c) fp.loc
d) fp.pos
Answer: b
Explanation: It gives the current position as an offset from the start of file.
7. 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)
Answer: b
Explanation: os.rename() is used to rename files.
8. How do you delete a file?
a) del(fp)
b) fp.delete()
c) os.remove(‘file’)
d) os.delete(‘file’)
Answer: c
Explanation: os.remove() is used to delete files.
9. How do you change the file position to an offset value from the start?
a) fp.seek(offset, 0)
b) fp.seek(offset, 1)
c) fp.seek(offset, 2)
d) none of the mentioned
Answer: a
Explanation: 0 indicates that the offset is with respect to the start.
10. 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
Answer: d
Explanation: seek() takes at least one argument.