Reading and Writing Files Questions and Answers

Practice Mode
Showing 10 of 25 questions
Q1
Which function is used to open a file in Python?
  • A file_open()
  • B open()
  • C read_file()
  • D file()
Answer: Option B
Explanation: The open() function is used to open files in Python and returns a file object.
Q2
Which mode opens a file for reading only?
  • A "w"
  • B "r"
  • C "a"
  • D "x"
Answer: Option B
Explanation: "r" mode opens a file for reading only and is the default mode.
Q3
Which mode creates a new file for writing and returns error if file exists?
  • A "w"
  • B "a"
  • C "x"
  • D "r"
Answer: Option C
Explanation: "x" mode creates a new file and returns an error if the file already exists.
Q4
Which method reads the entire content of a file as a string?
  • A readline()
  • B readall()
  • C read()
  • D get()
Answer: Option C
Explanation: The read() method reads the entire content of a file and returns it as a string.
Q5
Which method reads one line from a file?
  • A read()
  • B readline()
  • C nextline()
  • D getline()
Answer: Option B
Explanation: The readline() method reads a single line from the file and returns it as a string.
Q6
Which method returns all lines in a file as a list?
  • A read()
  • B readlines()
  • C getlines()
  • D lines()
Answer: Option B
Explanation: The readlines() method reads all lines in a file and returns them as a list of strings.
Q7
Which mode opens a file for both reading and writing?
  • A "r"
  • B "w+"
  • C "r+"
  • D "a+"
Answer: Option C
Explanation: "r+" mode opens a file for both reading and writing.
Q8
What is the correct way to close a file in Python?
  • A file.close()
  • B close(file)
  • C file->close()
  • D close.file()
Answer: Option A
Explanation: The close() method is used to close an opened file and free up system resources.
Q9
Which statement automatically closes a file after usage?
  • A for
  • B while
  • C with
  • D using
Answer: Option C
Explanation: The with statement automatically closes the file when the block inside it is exited.
Q10
Which method writes a string to a file?
  • A writeline()
  • B put()
  • C write()
  • D output()
Answer: Option C
Explanation: The write() method writes a string to an opened file.
Questions and Answers for Competitive Exams Various Entrance Test