Python File Handling MCQ : Set 4

Python File Handling MCQ

1). What is the purpose of the following code?

				
					file = open('file.txt')
data = file.read().split()
m_num = []
for val in data:
    if val.isnumeric():
        if len(val) == 10:
            m_num.append(val)
print("Mobile numbers in the file: ", m_num)
				
			

a) Read the contents of the file and split them into a list
b) Extract all the numeric values from the file
c) Filter and collect 10-digit mobile numbers from the file
d) Print the content of the file

Correct answer is: c) Filter and collect 10-digit mobile numbers from the file
Explanation: The given code opens a file named ‘file.txt’ and reads its contents using the `read()` method. The content is then split into a list of individual words using the `split()` method. Next, an empty list `m_num` is created to store the mobile numbers. The code then iterates through each value in the list `data` and checks if it is a numeric value using the `isnumeric()` method. If the value is numeric, it further checks if its length is equal to 10 digits. If both conditions are met, the value is considered a 10-digit mobile number and is appended to the `m_num` list. Finally, the code prints the collected mobile numbers using the `print()` function. The purpose of this code snippet is to filter and extract 10-digit mobile numbers from the given file.

2). What is the purpose of the following code?

				
					file = open("file name", "r")
lines = file.readlines()
count = 0
for line in lines:
    count += 1
print("Total number of lines in the file: ", count)
				
			

a) To read the contents of a file and store them in a list
b) To count the number of characters in a file
c) To count the number of words in a file
d) To count the number of lines in a file

Correct answer is: d) To count the number of lines in a file
Explanation: The given code opens a file named “file name” in read mode using the `open()` function and assigns it to the `file` variable. Then, it uses the `readlines()` method to read all the lines from the file and stores them in a list called `lines`. Next, a variable `count` is initialized to 0. The code then iterates over each line in the `lines` list using a `for` loop. For each line, the `count` variable is incremented by 1, effectively counting the number of lines in the file. Finally, the total number of lines in the file is printed as output using the `print()` function.

3). What is the purpose of the following code?

				
					import os
info = os.stat('file.txt')
print("Size of the file: ", info.st_size)
				
			

a) To check if the file ‘file.txt’ exists in the current directory
b) To get the size of the file ‘file.txt’
c) To delete the file ‘file.txt’
d) To rename the file ‘file.txt’

Correct answer is: b) To get the size of the file ‘file.txt’
Explanation: The code uses the `os.stat()` function from the `os` module to retrieve the file information for the file named ‘file.txt’. The `os.stat()` function returns a named tuple with several attributes representing file information. In this case, the code accesses the `st_size` attribute of the `info` named tuple, which corresponds to the size of the file in bytes. The code then prints the size of the file to the console using the `print()` function. Therefore, the purpose of this code snippet is to obtain and display the size of the file ‘file.txt’.

4). What is the purpose of the following code?

				
					tup = ('1', '2', '3')
f = open('file.txt', 'w')
f.write(" ".join(tup))
f.close()
				
			

a) It creates a tuple containing three elements: ‘1’, ‘2’, and ‘3’.
b) It opens a file named ‘file.txt’ in write mode.
c) It writes the string representation of the tuple elements separated by a space to the file.
d) It closes the file after writing the data.

Correct answer is: c) It writes the string representation of the tuple elements separated by a space to the file.
Explanation: It creates a tuple named `tup` containing three elements: ‘1’, ‘2’, and ‘3’. It opens a file named ‘file.txt’ in write mode using the `open()` function with the mode parameter set to ‘w’. It writes the string representation of the elements in the tuple `tup` to the file by using the `write()` method. The elements are joined together using the `join()` method with a space as the separator. Finally, it closes the file using the `close()` method to ensure that all the changes are saved.

5). What is the purpose of the following code?

				
					f = open('file.txt','r')
print(f.closed)
f.close()
print(f.closed)
				
			

a) To open a file in read mode, check if the file is closed, and then close the file
b) To open a file in write mode, check if the file is closed, and then close the file
c) To open a file in append mode, check if the file is closed, and then close the file
d) To open a file in read mode and check if the file is closed, without closing the file

Correct answer is: a) To open a file in read mode, check if the file is closed, and then close the file
Explanation: The code opens a file named ‘file.txt’ in read mode using the `open()` function with the mode parameter set to ‘r’. The `print(f.closed)` statement is used to check the status of the file object’s `closed` attribute, which indicates whether the file is closed or not. Since the file is just opened, the output will be `False`. The `f.close()` statement is used to explicitly close the file. The `print(f.closed)` statement is called again to check the status of the file object’s `closed` attribute after closing the file. Since the file is closed, the output will be `True`.

6). What is the purpose of the following code?

				
					file = open('file.txt')
words = file.read().split()
list1 = []
for word in words:
    for char in word:
        list1.append(char)
print("Characters in the file in the list: ", list1)
				
			

a) To count the number of characters in a file.
b) To extract all the words from a file.
c) To create a list of characters from a file.
d) To concatenate all the words in a file.

Correct answer is: c) To create a list of characters from a file.
Explanation: The given code opens a file named ‘file.txt’ using the `open()` function without specifying a mode, which defaults to read mode (‘r’). It then reads the content of the file using the `read()` method and splits the content into a list of words using the `split()` method. The code initializes an empty list `list1` to store the characters from the file. It then iterates over each word in the `words` list and, for each word, iterates over each character using a nested loop. It appends each character to the `list1` using the `append()` method. Finally, it prints the message “Characters in the file in the list: ” followed by the `list1` containing all the characters from the file.

7). What is the purpose of the following code?

				
					data = data2 = ""
with open('file1.txt') as f:
    data = f.read()
with open('file2.txt') as f:
    data2 = f.read()
data += "\n"
data += data2

with open ('file3.txt', 'w') as f:
    f.write(data)
				
			

a) It reads the contents of two files and concatenates them.
b) It copies the contents of one file to another file.
c) It appends the contents of one file to another file.
d) It deletes the contents of two files and saves the result in another file.

Correct answer is: a) It reads the contents of two files and concatenates them.
Explanation: The given code snippet opens two files, ‘file1.txt’ and ‘file2.txt’, and reads their contents using the `read()` method. The contents of the two files are stored in the variables `data` and `data2` respectively. The code then appends a newline character (`”\n”`) to the `data` variable and concatenates the contents of `data2` to `data`. Finally, the code opens a file named ‘file3.txt’ in write mode using the `open()` function with the `’w’` argument. It writes the concatenated data to ‘file3.txt’ using the `write()` method, effectively saving the combined contents of ‘file1.txt’ and ‘file2.txt’ in ‘file3.txt’.

8). What is the purpose of the following code?

				
					file = open('file name')
words = file.read().split()
count = 0
for word in words:
    for char in word:
        if char.isalpha():
            count += 1
print("Total number of characters in the file: ", count)
				
			

a) Count the number of lines in the file.
b) Count the number of words in the file.
c) Count the number of alphabetic characters in the file.
d) Count the number of non-alphabetic characters in the file.

Correct answer is: c) Count the number of alphabetic characters in the file.
Explanation: The given code opens a file and reads its contents. It then splits the contents into words and initializes a counter, `count`, to zero. The code then iterates over each word and checks each character in the word. If the character is alphabetic (a letter), it increments the `count` by 1. Finally, it prints the total number of alphabetic characters in the file. Therefore, the purpose of this code is to count the number of alphabetic characters in the file.

9). What is the purpose of the following code?

				
					file = open('file.txt')
words = file.read().split()
count = 0
for word in words:
    for char in word:
        if char.isupper():
            count += 1
print("Total number of uppercase characters in the file: ", count)
				
			

a) Count the total number of words in the file.
b) Count the total number of lines in the file.
c) Count the total number of lowercase characters in the file.
d) Count the total number of uppercase characters in the file.

Correct answer is:
d) Count the total number of uppercase characters in the file.
Explanation: `file = open(‘file.txt’)`: This line opens the file named “file.txt” in the default mode (‘r’), creating a file object called `file`. `words = file.read().split()`: The `read()` method is used to read the content of the file, and `split()` is called to split the content into a list of words. The list of words is stored in the variable `words`. `count = 0`: A variable `count` is initialized to 0 to keep track of the number of uppercase characters. `for word in words:`: This starts a loop to iterate over each word in the `words` list. `for char in word:`: This nested loop iterates over each character in the current word. `if char.isupper():`: The `isupper()` method is called on each character to check if it is an uppercase character. If the condition in step 6 is `True`, the code increments the `count` variable by 1. After both loops complete, the code prints the total number of uppercase characters found in the file.

10). What is the purpose of the following code?

				
					file = open('file.txt')
words = file.read().split()
count = 0
for word in words:
    for char in word:
        if char.islower():
            count += 1
print("Total number of lowercase characters in the file: ", count)
				
			

a) Count the total number of characters in the file
b) Count the total number of words in the file
c) Count the total number of uppercase characters in the file
d) Count the total number of lowercase characters in the file

Correct answer is: d) Count the total number of lowercase characters in the file
Explanation: The given code opens a file named ‘file.txt’ and reads its content. The content is then split into individual words. The variable `count` is initialized to 0. Next, a nested loop iterates over each word and each character within the word. The `if` statement checks if the character is lowercase using the `islower()` method. If it is lowercase, the `count` variable is incremented. Finally, the code prints the total number of lowercase characters in the file using the `print()` statement.

11). What is the purpose of the following code?

				
					file = open('file name')
words = file.read().split()
count = 0
for word in words:
    for char in word:
        if char.isnumeric():
            count += 1
print("Total number of digits in the file: ", count)
				
			

a) Count the total number of words in the file.
b) Calculate the average word length in the file.
c) Determine the frequency of each digit in the file.
d) Count the total number of digits in the file.

Correct answer is: d) Count the total number of digits in the file.
Explanation: The given code opens a file using the ‘file name’ and reads its contents. It then splits the content into individual words and initializes a counter variable, `count`, to keep track of the number of digits found in the file. The code then iterates over each word in the file. For each word, it iterates over each character and checks if the character is numeric using the `isnumeric()` method. If a character is numeric, the counter `count` is incremented. Finally, the code prints the total number of digits found in the file. Therefore, the purpose of the code is to count the total number of digits in the file and display the result.

12). What is the purpose of the following code?

				
					file = open('file.txt')
file.readline()
print("Position of a cursor in the file: ", file.tell())
				
			

a) To open the file ‘file.txt’ in read mode
b) To open the file ‘file.txt’ in write mode
c) To read a line from the file ‘file.txt’
d) To print the current position of the file cursor

Correct answer is: d) To print the current position of the file cursor
Explanation: The given code opens a file named ‘file.txt’ using the `open()` function without specifying the mode, which defaults to read mode. The `file.readline()` method is then called to read a single line from the file. Finally, the `file.tell()` method is used to retrieve the current position of the file cursor, and it is printed using the `print()` function. The purpose of this code snippet is to determine and display the position of the file cursor within the file after reading a line.

13). What is the purpose of the following code?

				
					file = open('file.txt')
file.readline()
print("Position of a cursor in the file: ",file.tell())
file.seek(10)
print("Position of a cursor in the file: ",file.tell())
				
			

a) To open a file and read its contents line by line.
b) To retrieve the current position of the file cursor.
c) To move the file cursor to a specific position.
d) To print the contents of the file starting from a specific position.

Correct answer is: c) To move the file cursor to a specific position.
Explanation: The code opens a file named “file.txt” using the `open()` function. It then reads a single line from the file using the `readline()` method, although this line is not utilized further. The `tell()` method is used to retrieve the current position of the file cursor, which represents the byte offset from the beginning of the file. The code then uses the `seek()` method to move the file cursor to a specific position, in this case, position 10. Finally, the `tell()` method is called again to print the updated position of the file cursor. Therefore, the purpose of this code snippet is to demonstrate the movement of the file cursor to a specific position within the file.

14). What is the purpose of the following code?

				
					file = open('file.txt')
data = list(file.readlines())
for line in reversed(data):
    print(line)
				
			

a) To open a file and print its contents in reverse order.
b) To open a file and store its contents in a list.
c) To open a file and print its contents line by line.
d) To open a file and append its contents to an existing list.

Correct answer is: a) To open a file and print its contents in reverse order.
Explanation: The given code snippet opens a file named ‘file.txt’ using the `open()` function and assigns it to the variable `file`. It then reads the contents of the file using the `readlines()` method and converts it into a list by using the `list()` function. The list of lines is stored in the variable `data`. The subsequent for loop iterates over the `data` list in reverse order using the `reversed()` function. Inside the loop, each line is printed using the `print()` function. As a result, the code prints the contents of the ‘file.txt’ file in reverse order, displaying each line on a separate line of the output.

15). What is the purpose of the following code?

				
					file = open('file name')
words = file.read().split()
vowels = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']
count = 0
for word in words:
    for char in word:
        if char in vowels:
            count += 1
print("Total number of vowels in the file: ", count)
				
			

a) Count the total number of words in a file
b) Count the total number of lines in a file
c) Count the total number of vowels in a file
d) Count the total number of consonants in a file

Correct answer is: c) Count the total number of vowels in a file
Explanation: The code begins by opening a file using the `open()` function and assigning it to the `file` variable. The file name is specified as `’file name’` (please note that the actual file name would be provided in place of `’file name’`). The `file.read()` method is used to read the entire contents of the file as a single string. The `split()` method is then called on the string obtained from `file.read()` to split it into a list of words. By default, it splits the string at whitespace characters. The code initializes a list called `vowels` containing all the vowels in both lowercase and uppercase.A variable called `count` is initialized to 0. This variable will be used to keep track of the number of vowels encountered.The code then iterates over each word in the `words` list using a nested loop. Within the nested loop, each character in the current word is checked to see if it is present in the `vowels` list. If a character is found in the `vowels` list, it means it is a vowel, and the `count` variable is incremented by 1.Finally, the total number of vowels found in the file is printed using the `print()` function.

16). What is the purpose of the following code?

				
					file = open('file.txt')
words = file.read().split()
for word in words:
    if len(word) < 5:
        print(word, end=" ")
				
			

a) Open a file named ‘file.txt’ and read its content.
b) Open a file named ‘file.txt’ and write to it.
c) Count the number of words in a file named ‘file.txt’.
d) Print all words from a file named ‘file.txt’ that have a length less than 5.

Correct answer is: d) Print all words from a file named ‘file.txt’ that have a length less than 5.
Explanation: The code opens a file named ‘file.txt’ using the `open()` function and reads its content. The content is then split into a list of words using the `split()` method. The code then iterates over each word in the list and checks if its length is less than 5 characters. If a word satisfies the condition, it is printed using the `print()` function with the `end` parameter set to a space character. Therefore, the code’s purpose is to print all words from the file ‘file.txt’ that have a length less than 5.

17). What is the purpose of the following code?

				
					f1 = open("file.txt", "r")
data = f1.read()
data = data.replace(" ", "_")
f2 = open("file1.txt", "w")
f2.write(data)
				
			

a) Count the number of spaces in a text file and replace them with underscores.
b) Open a file named “file.txt” in read mode, replace all spaces with underscores, and save the modified content in a new file named “file1.txt”.
c) Open a file named “file.txt” in write mode, replace all underscores with spaces, and save the modified content in the same file.
d) Read the content of a file named “file.txt” and write it to a new file named “file1.txt” without any modifications.

Correct answer is: b) Open a file named “file.txt” in read mode, replace all spaces with underscores, and save the modified content in a new file named “file1.txt”.
Explanation: Opens a file named “file.txt” in read mode using the `open()` function and assigns it to the variable `f1`. Reads the entire content of the file using the `read()` method and stores it in the variable `data`. Replaces all occurrences of spaces with underscores in the `data` string using the `replace()` method. Opens a new file named “file1.txt” in write mode using the `open()` function and assigns it to the variable `f2`. Writes the modified `data` string to the “file1.txt” file using the `write()` method.

Leave a Comment