File Handling in Python MCQ Quiz - Objective Question with Answer for File Handling in Python - Download Free PDF

Last updated on Apr 15, 2025

File Handling MCQs dive into the principles of reading, writing, and manipulating files across different programming languages. This knowledge forms an integral part of software development and is frequently tested in competitive examinations. These MCQs are designed to refine your understanding of file handling concepts and their applications, helping you to translate theory into practice. Strengthen your skill set by solving File Handling MCQs with answers right away.

Latest File Handling in Python MCQ Objective Questions

File Handling in Python Question 1:

Which offset of seek() method in the following is not valid?

  1. 0-is for beginning of file.
  2. 1-the middle position of the file.
  3. 2-for end of file.
  4. 1- for current position of file pointer.

Answer (Detailed Solution Below)

Option 2 : 1-the middle position of the file.

File Handling in Python Question 1 Detailed Solution

- guacandrollcantina.com

The correct answer is Option 2: 1-the middle position of the file.

key-point-image Key Points
  • The seek() method in Python is used to move the file pointer to a specific position within a file.
  • The method has three valid offsets:
    • 0: Move the file pointer to the beginning of the file.
    • 1: Move the file pointer to the current position.
    • 2: Move the file pointer to the end of the file.
  • There is no offset for moving the pointer to the "middle position" of the file; hence, Option 2 is not valid.
additional-information-image Additional Information
  • Python's seek() method is part of the built-in file handling functions.
  • Here is an example of how the seek() method can be used:
    
    # Open a file in read mode
    file = open('example.txt', 'r')
    
    # Move the file pointer to the beginning
    file.seek(0)
    
    # Move the file pointer to the end
    file.seek(0, 2)
    
    # Move the file pointer to the current position
    file.seek(0, 1)
    
    # Close the file
    file.close()
                
  • Understanding the use of seek() is crucial for efficient file manipulation in Python.

File Handling in Python Question 2:

Which of the file mode in the following is invalid for a text-file?

  1. a
  2. w
  3. r
  4. ab

Answer (Detailed Solution Below)

Option 4 : ab

File Handling in Python Question 2 Detailed Solution

The correct answer is ab.

key-point-image Key Points
  • In text file handling, various modes are used to specify the type of operations that can be performed on the file.
  • The common file modes for text files include:
    • r: Opens the file for reading. If the file does not exist, an error is raised.
    • w: Opens the file for writing. If the file exists, it is truncated to zero length. If the file does not exist, a new file is created.
    • a: Opens the file for appending. The file pointer is at the end of the file if the file exists. If the file does not exist, it creates a new file for writing.
  • The mode ab is invalid for a text file because the mode 'ab' is used for binary files, not text files. In binary mode, 'a' stands for appending, and 'b' stands for binary, which is not applicable for text file operations.
additional-information-image Additional Information
  • Text files are used to store data in a readable format using characters. Binary files store data in a binary format, which is not human-readable.
  • It is essential to use the correct file mode to prevent errors and ensure the correct handling of the file data.
  • Other file modes for binary files include 'rb' (read binary), 'wb' (write binary), and 'ab' (append binary).
  • Using the wrong file mode can lead to data corruption or file handling errors.

File Handling in Python Question 3:

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

  1. ab
  2. rw
  3. r+
  4. w+

Answer (Detailed Solution Below)

Option 2 : rw

File Handling in Python Question 3 Detailed Solution

The correct answer is rw.

key-point-image Key Points

  • In most programming languages, file opening modes are predefined strings that indicate the mode in which the file should be opened.
  • Commonly used file opening modes include:
    • r: Open for reading (default).
    • w: Open for writing, truncating the file first.
    • a: Open for writing, appending to the end of the file if it exists.
    • r+: Open for reading and writing.
    • w+: Open for reading and writing, truncating the file first.
    • a+: Open for reading and writing, appending to the end of the file if it exists.
  • The mode "rw" is not a standard file opening mode in most programming languages; it is not recognized and will likely cause an error.
  • The correct modes for reading and writing at the same time are "r+", "w+", and "a+".

additional-information-image Additional Information

  • Using the correct file mode is crucial for ensuring the desired file operations are performed correctly.
  • Improper usage of file modes can lead to data loss, file corruption, or runtime errors.
  • Always refer to the documentation of the programming language being used to understand the supported file modes.

File Handling in Python Question 4:

Which method from below will take a file pointer to nth character with respect to r position?

  1. fp.seek(r)
  2. fp.seek(n)
  3. fp.seek(n,r)
  4. seek(n,r).fp

Answer (Detailed Solution Below)

Option 3 : fp.seek(n,r)

File Handling in Python Question 4 Detailed Solution

The correct answer is fp.seek(n, r).

key-point-imageKey Points

  • The fp.seek(n, r) method in Python is used to change the file pointer position.
  • It takes two arguments: n (the number of bytes to move) and r (the reference position).
  • The reference position can be one of three values:
    • 0: Start of the file.
    • 1: Current position.
    • 2: End of the file.
  • For example, fp.seek(10, 0) moves the file pointer to the 10th byte from the start of the file.

additional-information-imageAdditional Information

  • The fp.seek() method is part of the file object in Python.
  • It is commonly used in file handling for reading and writing operations.
  • Using fp.seek(), you can easily navigate to different positions in a file, which is useful for modifying specific parts of a file.
  • Example source code:
    
    # Open a file in read mode
    with open('example.txt', 'r') as fp:
        # Move the file pointer to the 5th byte from the start
        fp.seek(5, 0)
        # Read the content from the current file pointer position
        content = fp.read()
        print(content)
    
                

File Handling in Python Question 5:

Consider the following code and specify the correct order of the statements to be written

(A) f.write("CUET EXAMINATION")

(B) f=open("CUET.TXT", "w")

(C) print("Data is Written Successfully")

(D) f.close()

Choose the correct answer from the options given below:

  1. (A), (B), (C), (D)
  2. (B), (A), (C), (D) 
  3. (B), (D), (C), (A) 
  4. (B), (D), (A), (C)

Answer (Detailed Solution Below)

Option 2 : (B), (A), (C), (D) 

File Handling in Python Question 5 Detailed Solution

The correct answer is Option 2.

key-point-image Key Points

  • The correct sequence of operations to write to a file in Python is:
    • (B) Open the file in write mode.
    • (A) Write the data to the file.
    • (C) Print a success message.
    • (D) Close the file.
  • The correct sequence ensures that the file is properly opened, the data is written, a success message is printed, and the file is closed properly to avoid any data corruption or memory leaks.

additional-information-image Additional Information

  • Opening a file using open("filename", "w") creates the file if it does not exist and truncates the file if it does exist.
  • Using f.write("data") writes the specified data to the file.
  • print("message") outputs a message to the console.
  • Calling f.close() ensures that the file is properly closed, which is important for freeing up system resources and flushing any buffered data to the disk.

Example Code:


# Step (B): Open the file in write mode
f = open("CUET.TXT", "w")

# Step (A): Write data to the file
f.write("CUET EXAMINATION")

# Step (C): Print a success message
print("Data is Written Successfully")

# Step (D): Close the file
f.close()

    

Top File Handling in Python MCQ Objective Questions

File Handling in Python Question 6:

What is the full form of CSV file?

  1. Colon Separated Values
  2. Context Separated Values
  3. Comma Separated Values
  4. Caps Separated Values

Answer (Detailed Solution Below)

Option 3 : Comma Separated Values

File Handling in Python Question 6 Detailed Solution

The correct answer is option 3.

Concept:

CSV Full Form:

  • The Comma Separated Value (CSV) format is a text file that contains data. It makes it easier to store data in a table-like format. The CSV extension is used to identify CSV files.
  • CSV files are used to transfer huge databases between applications while adhering to a precise format. CSV files may be opened with any text editor, such as Notepad or Excel.

Characteristics:

  • Each data item is entered on a different line. If the record is too long, it may span numerous lines.
  • The data fields are separated by commas.
  • A set of double quotes contains the fields that contain commas and are separated by double-quotes.
  • The fields containing double quotes are contained in a set of double-quotes.
  • The space characters that appear adjacent to built-in commas are ignored.

Hence the correct answer is Comma Separated Values

File Handling in Python Question 7:

Which one is the following advantage of using with clause while opening a file.

  1. The file write automatically.
  2. The file read automatically.
  3. The file closed automatically.
  4. The file delete automatically.

Answer (Detailed Solution Below)

Option 3 : The file closed automatically.

File Handling in Python Question 7 Detailed Solution

Correct option is The file closed automatically

CONCEPT:

To read or write a file, first we need to open it.

Python provides a function open(), which returns a file object with which we can read and write in the file. But in the end, we need to close the file using close() function call.

If we don’t call the close() function, the file will remain open, and its object will be consuming the memory of our process.

Therefore it is a standard practice to close an open file as a closed file reduces the risk of being unwarrantedly modified or read.

The “with statement” creates an execution block and the object created in the with statement will be destroyed when the execution block ends.

 

Advantages of calling open() using “with statement”:

  • Files gets closed automatically.
  • Fewer chances of bugs due to coding error
  • Open multiple files in a single “with statement”

File Handling in Python Question 8:

Which method is used to remove/delete a file?

  1. remove()
  2. flush()
  3. fname()
  4. delete()

Answer (Detailed Solution Below)

Option 1 : remove()

File Handling in Python Question 8 Detailed Solution

The correct answer is option 1.

Concept:

Python has a variety of methods and functions for deleting files and directories. The file can be removed based on the needs of the user. Python provides a number of techniques, including –

Using os.remove():

In Python, the os. remove() function is used to remove or delete a file path. A directory cannot be removed or deleted using this approach. If the supplied path is a directory, the procedure will throw an OSError.

Syntax:

os.remove(path, *, dir_fd = None)

Using os.rmdir():

In Python, the os. rmdir() function is used to remove or delete an empty directory. If the supplied path is not an empty directory, an OSError will be produced.

Syntax:

os.rmdir(path, *, dir_fd = None)

Using shutil.rmtree():

In python, shutil. rmtree() is used to delete an entire directory tree, the path must point to a directory (but not a symbolic link to a directory).

Syntax:

shutil.rmtree(path, ignore_errors=False, onerror=None)

Hence the correct answer is remove().

File Handling in Python Question 9:

You are given the text file, file1.txt whose contents are:

hello everyone

today is a monday

all the best for your exams

 

What will be the output of the following code?

myfile = open("file1.txt", "r")

str = myfile.readline(6)

str = myfile.readline()

str = myfile.readline(8)

print(str)

myfile.close()

  1. today is

  2. hello
  3. hello ev
  4. hello everyone

Answer (Detailed Solution Below)

Option 1 :

today is

File Handling in Python Question 9 Detailed Solution

Correct answer: Option 1

Explanation:

  • The first readline() returns ‘hello ‘. The file pointer now points at the start of ‘everyone’.
  • The second readline() returns till the end of the line from where the file pointer is located. Thus, it returns ‘everyone’.
  • After this, the file pointer is at the start of the second line. So, the third readline() prints the first 8 characters from the second line.
  • Hence, the final contents in str are ‘today is’.

Important points:

  • After the execution of a readline() statement, the file pointer points to the next line in the file.
  • If n characters are specified, the file pointer is at the n+1 location on the same line.

File Handling in Python Question 10:

The following functions are used to access data randomly.

  1. open() and readlines()
  2. seek() and read()
  3. seek() and tell()
  4. tell() and read()

Answer (Detailed Solution Below)

Option 3 : seek() and tell()

File Handling in Python Question 10 Detailed Solution

The correct answer is option 3.

Concept:

Setting Offsets in a File:

The functions we've learned so far are utilized to access data sequentially from a file. However, if we wish to retrieve data at random, Python has the seek() and tell() methods.

The tell() method:

This function returns a number indicating the file object's current location in the file. The supplied position is the byte location from the start of the file to the current position of the file object.

syntax:

file_object.tell()

The seek() method:

This function is used to place a file object at a certain location within a file. 

syntax:

file_object.seek(offset [, reference_point])
Here offset is the number of bytes by which the file object is to be moved. reference_point indicates the starting position of the file object.
Hence the correct answer is seek() and tell().

File Handling in Python Question 11:

A ___________ method is used to position the file object at a particular position in a file.

  1. tell()
  2. read()
  3. input()
  4. seek()

Answer (Detailed Solution Below)

Option 4 : seek()

File Handling in Python Question 11 Detailed Solution

The correct answer is option 4.

Concept:

Setting Offsets in a File:

The functions we've learned so far are utilized to access data sequentially from a file. However, if we wish to retrieve data at random, Python has the seek() and tell() methods.

The seek() method:

This function is used to place a file object at a certain location within a file.  seek() method is used to position the file object at a particular position in a file.

syntax:

file_object.seek(offset [, reference_point])
Here offset is the number of bytes by which the file object is to be moved. reference_point indicates the starting position of the file object.
Hence the correct answer is seek().

Additional InformationThe tell() method: 

This function returns a number indicating the file object's current location in the file. The supplied position is the byte location from the start of the file to the current position of the file object.

syntax:

file_object.tell()

File Handling in Python Question 12:

The following code will perform which operation?

object.readline(10)

  1. Read first 10 lines
  2. Read first 10 characters of line
  3. Read first 10 bits in line
  4. Read first 10 words of line

Answer (Detailed Solution Below)

Option 2 : Read first 10 characters of line

File Handling in Python Question 12 Detailed Solution

The correct answer is option 2.

Concept:

Python File readline() Method:

The readlines() are used to read all of the lines at once and return them as string elements in a list. This method is useful for tiny files since it reads the entire file content to memory and then splits it into individual lines. We may go through the list and use the strip() method to remove the newline 'n' character.

Syntax:

file.readline(size)

Here size is Optional. The number of bytes from the line to return. Default -1, which means the whole line.

Explanation:

object.readline(10)

readline reads a line of the file and returns it in the form of the string. It takes a parameter 10, which specifies the maximum number of bytes that will be read. However, does not reads more than one line, even if 10 exceeds the length of the line.

So it read the first 10 characters of line.

Hence the correct answer is to read the first 10 characters of the line.

File Handling in Python Question 13:

Which method is used to rename the file or folder?

  1. filename()
  2. flush()
  3. fname()
  4. rename()

Answer (Detailed Solution Below)

Option 4 : rename()

File Handling in Python Question 13 Detailed Solution

The correct answer is option 4.

Concept:

Python rename() file is a function in Python programming that is used to rename a file or a directory. The Python rename() file function can be used by giving two parameters, src (Source) and dst (Destination) (Destination).

Syntax :

This is the syntax for os.rename() method.

os.rename(src, dst)

Parameters

  • src: The source is the name of the file or directory. It has to exist already.
  • dst: The destination is the new name of the file or directory to be renamed.

Example:

import os os.rename('lmstestbook.txt','lmstestbook.txt')

Hence the correct answer is rename()

File Handling in Python Question 14:

Which method is used to find the name of the current working directory in Python?

  1. dir()
  2. getcwd()
  3. fname()
  4. getcur()

Answer (Detailed Solution Below)

Option 2 : getcwd()

File Handling in Python Question 14 Detailed Solution

The correct answer is option 2.

Concept:

getcwd():

  • Obtaining the directory on which work is presently being performed in a Python application is critical. This is readily accomplished by utilizing the os. getcwd ().
  • Every process that runs under an operating system has an associated working directory, which is referred to as the process's current working directory.

Syntax:

The syntax for getcwd() method:

cwd = os.getcwd()

Parameters:

NA

Return Value:

This method returns the current working directory of a process.

Example: Open a file and print the content:

f = open("demofile.txt", "r")
print(f.read())

Output:

The current working directory is:
/Users/Python

Hence the correct answer is getcwd().

File Handling in Python Question 15:

Which of the following is right syntax to open a file.txt in append mode?

  1. file_object = open("file.txt", "a")
  2. file_object = open(file.txt, 'a')
  3. file_object = open("file.txt")
  4. file_object = open("file", "a")

Answer (Detailed Solution Below)

Option 1 : file_object = open("file.txt", "a")

File Handling in Python Question 15 Detailed Solution

The correct answer is option 1.

Concept:

  • Use the built-in open() method to open the file.
  • The open() function returns a file object with a read() method for accessing the file's content.

The open() function has many parameters but you’ll be focusing on the first two.

Syntax:

open(path_to_file, mode)

  • path_to_file parameter specifies the path to the text file.
  • mode are read/write/append
Mode Description
'r'   Open for text file for reading text
'w' Open a text file for writing text'
'a' Open a text file for appending text

The handle is at the end of the file when the file is opened in append mode. The new data will be added at the end, following the old data. Let's look at an example to show how to write mode differs from the append mode.

file_object = open("file.txt", "a")

The above line is true for the right syntax to open a file.txt in append mode.

Hence the correct answer is file_object = open("file.txt", "a").

Get Free Access Now
Hot Links: all teen patti game teen patti mastar teen patti rummy 51 bonus