In: Computer Science
This is a python 3.0 question, there are either 1 or 2 answers for each sub-question.
Part i) Which of the following statements regarding the opening modes of a file are true?
Select one or more:
a. When you open a file for writing, if the file does not exist, a new file is created.
b. When you open a file for writing, if the file exists, the existing file is overwritten with the new file.
c. When you open a file for writing, if the file does not exist, an error occurs.
d. When you open a file for reading, if the file does not exist, the program will open an empty file.
e. When you open a file for reading, if the file does not exist, an error occurs.
Part ii) What is the data type of the value returned by the read() or readline() methods of a file object, assuming that file object is associated to a pure text file?
Select one or more:
a. int
b. It depends on the data type of the values stored in the file.
c. list
d. str
Part iii) Which of the following methods of a file object reads the entire file into a single string?
Select one or more:
a. readline() if and only if there are no newline characters in the file
b. readlines()
c. read_file_to_str()
d. read()
Answer
Here is your answer, if you have any doubt please comment, i am here to help you.
1) Answer : A,B ,E
we can handle file in python using
open() function.The open()
function
takes two parameters; filename, and
mode.
#mode specified in double quotes.
"r" - Read - Default value. Opens a file for reading, error if the file does not exist
"w" - Write - Opens a file for writing and creates the file if it does not exist
"a" - Append - Opens a file for appending and creates the file if it does not exist
"x" - Create - Creates the specified file and returns an error if the file exists
2)
readlines():
method returns a list
containing each line in the file as a list item.
read() :this method will read entire file as str.
example:
So answer is C and D.
3) Answer , A and D,
readline() if and only if there are no newline characters in the file. Only take one line of the file and make it as str.
read() also take entire take as str.
readlines() will print list of strings
If you have any doubt please comment
Thanks in advance