Computer Science
Which of the following statements is/are true?
- When we open a file for reading, if the file does not exist, an error occurs.
- When we open a file for writing, if the file does not exist, a new file is created.
- When we open a file for writing, if the file exists, the existing file is overwritten with the new file.
- All of these.
Answer
All of these.
Reason — When we open a file for reading ('r' mode) that doesn't exist, Python raises an error (FileNotFoundError). When we open a file for writing ('w' mode) and the file doesn't exist, a new file is created with the specified name. If we open a file for writing ('w' mode) and the file already exists, the existing file is overwritten with the new file.
Related Questions
To open a file c:\test.txt for writing, we should use the statement:
- fobj = open("c:\test.txt", "w")
- fobj = open("c:\\test.txt", "w")
- fobj = open(file = "c:\test.txt", "w")
- fobj = open(file = "c:\\test.txt", "w")
To open a file c:\test.txt for appending data, we can give the statement:
- fobj = open("c:\\test.txt", "a")
- fobj = open("c:\\test.txt", "rw")
- fobj = open(file = "c:\test.txt", "w")
- fobj = open(file = "c:\\test.txt", "w")
To read two characters from a file object fobj, the command should be:
- fobj.read(2)
- fobj.read()
- fobj.readline()
- fobj.readlines()
To read the entire contents of the file as a string from a file object fobj, the command should be:
- fobj.read(2)
- fobj.read()
- fobj.readline()
- fobj.readlines()