Python File Handling MCQ : Set 3

Python FIle Handling MCQ

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

				
					f = open("file1", "a")
f.write("\nlearning python is fun")
f.close()
				
			

a) The code appends the string “learning python is fun” to the file named “file1” and then closes the file.
b) The code opens the file named “file1” for reading, writes the string “learning python is fun” to the file, and then closes the file.
c) The code creates a new file named “file1” and writes the string “learning python is fun” to the file, and then closes the file.
d) The code raises an error because the file “file1” does not exist.

Correct answer is: a) The code appends the string “learning python is fun” to the file named “file1” and then closes the file.
Explanation: In the given code, the file “file1” is opened in “append” mode by using the second argument “a” in the `open()` function. This allows the code to append content to the existing file rather than overwriting it. The `write()` method is then used to write the string “\nlearning python is fun” to the file, which adds a new line followed by the specified text. Finally, the `close()` method is called to close the file and ensure that any changes are saved.

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

				
					f = open("file1", "a")
f.write("\nlearning python is fun")
f.close()
				
			

a) The code appends the string “learning python is fun” to the file named “file1” and then closes the file.
b) The code opens the file named “file1” for reading, writes the string “learning python is fun” to the file, and then closes the file.
c) The code creates a new file named “file1” and writes the string “learning python is fun” to the file, and then closes the file.
d) The code raises an error because the file “file1” does not exist.

Correct answer is: a) The code appends the string “learning python is fun” to the file named “file1” and then closes the file.
Explanation: In the given code, the file “file1” is opened in “append” mode by using the second argument “a” in the `open()` function. This allows the code to append content to the existing file rather than overwriting it. The `write()` method is then used to write the string “\nlearning python is fun” to the file, which adds a new line followed by the specified text. Finally, the `close()` method is called to close the file and ensure that any changes are saved.

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

				
					file = open("file1", "r")
linesList = file.readlines()
for i in linesList[:3]:
    print(i)
				
			

a) It prints the first three lines of the file “file1”.
b) It prints the first three characters of each line in the file “file1”.
c) It prints the entire contents of the file “file1”.
d) It raises an error due to an incorrect file name.

Correct answer is: a) It prints the first three lines of the file “file1”.
Explanation: The code opens a file named “file1” in read mode using the `open()` function. It then reads all the lines from the file using the `readlines()` method and stores them in the `linesList` variable. The subsequent for loop iterates over the first three lines of the `linesList` and prints each line using the `print()` function. As a result, the code will output the first three lines of the file “file1”.

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

				
					import re
file = open("file name", "r") 
for line in file:
    s = line.strip()
    result = re.findall(r"[A-Za-z0-9._%+-]+"
                     r"@[A-Za-z0-9.-]+"
                     r"\.[A-Za-z]{2,4}", s)
    print(result)
				
			

a) Prints all the lines from the file.
b) Prints the email addresses found in each line of the file.
c) Prints the number of email addresses found in the file.
d) Raises an error due to an invalid regular expression.

Correct answer is: b) Prints the email addresses found in each line of the file.
Explanation: The given code reads a file line by line using a loop. For each line, it removes leading and trailing whitespaces using `line.strip()` and assigns the result to the variable `s`. Then, the regular expression `r”[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}”` is used to find email addresses within the line. The `re.findall()` function is used to find all non-overlapping matches of the regular expression pattern in the given string (`s`). The `re.findall()` function returns a list of all the email addresses found in the line. Each email address is a string matching the regular expression pattern. Finally, the code prints the `result`, which is the list of email addresses found in each line of the file.

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

				
					file = open('file name')
data = file.readlines()
print("1st line")
print(data[0])
				
			

a) It will raise a FileNotFoundError.
b) It will print “1st line” and then raise an IndexError.
c) It will print “1st line” and then print the first line of the file.
d) It will print “1st line” and then print an empty line.

Correct answer is: c) It will print “1st line” and then print the first line of the file.
Explanation: The given code opens a file named “file name” using the `open()` function and assigns the file object to the variable `file`. Then, it reads all the lines from the file using the `readlines()` method and stores them in the variable `data`. The next two lines of code print “1st line” and the first line of the file, respectively. Since the `readlines()` method reads all the lines of the file and stores them in a list, `data[0]` represents the first line of the file. Therefore, when `print(data[0])` is executed, it will print the content of the first line of the file. Hence, the output of the code will be “1st line” followed by the first line of the file.

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

				
					f1 = open('file1.txt', 'r')
f2 = open('file.txt', 'w')
  
cont = f1.readlines()
for i in range(0, len(cont)):
    if(i % 2 != 0):
        f2.write(cont[i])
    else:
        pass
  
f2.close()
				
			

a) The code reads the contents of the file named ‘file name’ and writes the odd-indexed lines to a new file named ‘file.txt’.
b) The code reads the contents of the file named ‘file.txt’ and writes the odd-indexed lines to a new file named ‘file name’.
c) The code reads the contents of the file named ‘file name’ and writes the even-indexed lines to a new file named ‘file.txt’.
d) The code reads the contents of the file named ‘file.txt’ and writes the even-indexed lines to a new file named ‘file name’.

Correct answer is: a) The code reads the contents of the file named ‘file1.txt’ and writes the odd-indexed lines to a new file named ‘file.txt’.
Explanation: The code opens two files: ‘file1.txt’ in read mode (`’r’`) and ‘file.txt’ in write mode (`’w’`). The `f1.readlines()` method reads all the lines from the file named ‘file name’ and stores them in the `count` variable as a list of strings. The `for` loop iterates over the indices of the `count` list using the `range()` function. For each iteration, the code checks if the index `i` is odd (`i % 2 != 0`). If the index is odd, it means the line is odd-indexed, and the code writes that line to the file named ‘file.txt’ using `f2.write(cont[i])`. If the index is even, the `else` block is executed, which does nothing (`pass` statement). Finally, the code closes the file named ‘file.txt’ using `f2.close()`. Therefore, the code reads the contents of the file named ‘file1.txt’ and writes only the odd-indexed lines to a new file named ‘file.txt’.

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

				
					with open('file.txt') as f:
    data_list = f.readlines()
    print(data_list)
				
			

a) `file.txt`
b) `data_list`
c) `[‘file.txt’]`
d) The contents of the ‘file.txt’ file as a list of strings

Correct answer is: d) The contents of the ‘file.txt’ file as a list of strings
Explanation: The code opens the file named ‘file.txt’ using the `open()` function and assigns it to the file object `f`. Then, the `readlines()` method is called on `f` to read the contents of the file and store them in the `data_list` variable as a list of strings. Finally, the `print()` function is used to display the contents of `data_list`. Therefore, the output will be the contents of the ‘file.txt’ file, each line represented as a string element in the `data_list` list.

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

				
					file = open('file.txt')
words = file.read().split()
max_len = len(max(words, key=len))
for word in words:
    if len(word) == max_len:
        print(word)
				
			

a) The code will result in an error.
b) The code will print all the words in the file.
c) The code will print the longest word in the file.
d) The code will print the number of words in the file.

Correct answer is: c) The code will print the longest word in the file.
Explanation: The code opens a file named ‘file.txt’ and reads its content. It splits the content into individual words and stores them in the `words` list. The variable `max_len` is assigned the length of the longest word in the list `words`, using the `max()` function and the `key=len` argument to compare the words based on their lengths. The subsequent `for` loop iterates over each word in the `words` list. It checks if the length of the word matches the `max_len` value. If the lengths match, the word is printed. Therefore, the code will print the longest word 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:
    if word == 'python':
        count += 1
print("Count of python in the file: ", count)
				
			

a) To open a file and read its contents into a list of words
b) To count the occurrences of the word ‘python’ in a file
c) To write the count of the word ‘python’ to a new file
d) To replace all occurrences of the word ‘python’ in a file

Correct answer is: b) To count the occurrences of the word ‘python’ in a file
Explanation: The given code opens a file named ‘file.txt’ using the `open()` function without specifying the mode, which defaults to read mode. It then reads the contents of the file using the `read()` method and splits the contents into a list of words using the `split()` method. Next, a variable `count` is initialized to 0. The code then iterates over each word in the `words` list using a `for` loop. Within the loop, it checks if the current word is equal to ‘python’. If it is, the `count` variable is incremented by 1. After iterating through all the words, the code prints the final count of the word ‘python’ using the `print()` function. Therefore, the purpose of this code is to count the occurrences of the word ‘python’ in the contents of the file ‘file.txt’ and display the count to the user.

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

				
					import random
lines = open('file.txt').read().splitlines()
data = random.choice(lines)
print(data)
				
			

a) To open a file and read its contents
b) To randomly select a line from a file and store it in the variable ‘data’
c) To shuffle the lines of a file and print the shuffled data
d) To generate random data and store it in a file named ‘file.txt’

Correct answer is: b) To randomly select a line from a file and store it in the variable ‘data’
Explanation: The code opens a file named ‘file.txt’ using the `open()` function and reads its contents using the `read()` method. It then splits the contents into separate lines using the `splitlines()` method and stores them in the `lines` variable. The `random.choice()` function is used to randomly select a line from the `lines` list and assign it to the `data` variable. Finally, the selected line is printed using the `print()` function. Therefore, the purpose of this code is to randomly choose a line from the file and store it in the variable ‘data’.

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

				
					with open('file1.txt', 'r') as data_file:
    with open('file2.txt', 'a') as output_file:
        for line in data_file:
            output_file.write(line.upper())

				
			

a) Copy the contents of ‘file1.txt’ to ‘file2.txt’.
b) Append the contents of ‘file1.txt’ to ‘file2.txt’, converting all text to uppercase.
c) Append the contents of ‘file2.txt’ to ‘file1.txt’, converting all text to uppercase.
d) Create a new file named ‘file2.txt’ and write the uppercase version of ‘file1.txt’ into it.

Correct answer is: b) Append the contents of ‘file1.txt’ to ‘file2.txt’, converting all text to uppercase.
Explanation: The code opens two files: ‘file1.txt’ in read mode (`’r’`) and ‘file2.txt’ in append mode (`’a’`). When the block is exited the `with` statement ensures that the files are automatically closed. The code then enters a loop where it iterates over each line in ‘file1.txt’. For each line, the `upper()` method is called to convert the text to uppercase. The converted line is then written to ‘file2.txt’ using the `write()` method. Therefore, the purpose of the code is to read the contents of ‘file1.txt’, convert the text to uppercase, and append the converted text to ‘file2.txt’.

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

				
					with open('file1.txt', 'r') as data_file:
        with open('file2.txt', 'a') as output_file:
            for line in data_file:
                output_file.write(line.lower())

				
			

a) It reads the content of ‘file1.txt’ and writes it to ‘file2.txt’ in lowercase.
b) It reads the content of ‘file1.txt’ and appends it to ‘file2.txt’ in lowercase.
c) It reads the content of ‘file1.txt’ and writes it to ‘file2.txt’ in uppercase.
d) It reads the content of ‘file1.txt’ and appends it to ‘file2.txt’ in uppercase.

Correct answer is: a) It reads the content of ‘file1.txt’ and writes it to ‘file2.txt’ in lowercase.
Explanation: The given code snippet opens two files, ‘file1.txt’ and ‘file2.txt’, using the `open()` function and file mode arguments (‘r’ for reading and ‘a’ for appending). The code then uses a nested context manager to read each line from ‘file1.txt’ and write it to ‘file2.txt’ in lowercase. The `for` loop iterates over the lines of ‘file1.txt’, and the `write()` method of the output_file object writes each line in lowercase to ‘file2.txt’. The code utilizes the `with` statement to ensure that the files are automatically closed after the code block is executed. Therefore, the purpose of the code is to convert the content of ‘file1.txt’ to lowercase and store it in ‘file2.txt’.

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

				
					file = open('file.txt')
words = file.read().split()
count = 0
for word in words:
    count += 1
print("Count of words in the file: ", count)
				
			

a) To open a file and read its content as a string
b) To count the number of lines in a file
c) To count the number of characters in a file
d) To count the number of words in a file

Correct answer is: d) To count the number of words in a file
Explanation: The 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, which returns the content as a string. The `split()` method is then used to split the string into a list of words based on whitespace. A count variable is initialized to 0, and a `for` loop iterates over each word in the `words` list. For each word encountered, the count variable is incremented by 1. Finally, the total count of words is printed using the `print()` function. Therefore, the purpose of this code is to open a file, read its content, split the content into words, and count the number of words in the file.

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

				
					import string, os
if not os.path.exists("letters"):
    os.makedirs("letters")
for letter in string.ascii_uppercase:
    with open(letter + ".txt", "w") as f:
        f.writelines(letter)
				
			

a) To create a directory named “letters” and write a separate file for each uppercase letter in the English alphabet, where each file contains only the corresponding letter.
b) To read existing files in the “letters” directory and write the uppercase letters of the English alphabet into them.
c) To create a directory named “letters” and write all uppercase letters of the English alphabet into a single file named “letters.txt”.
d) To check if the “letters” directory exists and write all uppercase letters of the English alphabet into a single file named “letters.txt”.

Correct answer is: a) To create a directory named “letters” and write a separate file for each uppercase letter in the English alphabet, where each file contains only the corresponding letter.
Explanation: The code first checks if the directory named “letters” exists using `os.path.exists()`. If the directory doesn’t exist, it is created it using `os.makedirs()`. Then, it iterates through each uppercase letter of the English alphabet using `string.ascii_uppercase`. Within the loop, it opens a file with the name of the current letter concatenated with “.txt” in write mode using `open()` with the “w” argument. It uses a `with` statement to ensure proper file handling, automatically closing the file after writing. It writes the current letter to the file using `f.writelines()`. As a result, the code creates a separate file for each uppercase letter in the “letters” directory, where each file contains only the corresponding letter.

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

				
					file = open('file.txt')
words = file.read().split()
even = []
odd = []
for word in words:
    if len(word) % 2 == 0:
        even.append(word)
    else:
        odd.append(word)
print("Words having even length: ", even)
print("Words having odd length: ", odd)
				
			

a) Count the total number of words in the ‘file.txt’ file.
b) Split the contents of the ‘file.txt’ file into a list of words.
c) Separate the words with even and odd lengths from the ‘file.txt’ file.
d) Print the contents of the ‘file.txt’ file as a single string.

Correct answer is: c) Separate the words with even and odd lengths from the ‘file.txt’ file.
Explanation: The given code opens a file named ‘file.txt’ using the `open()` function and assigns the file object to the variable `file`. It then reads the contents of the file using the `read()` method and splits the contents into a list of words using the `split()` method. The empty lists `even` and `odd` are initialized to store words with even and odd lengths, respectively.

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

				
					file = open('file.txt')
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 not in vowels:
            count += 1
print("Total number of consonants in the file: ", count)
				
			

a) Count the total number of vowels in the given file
b) Count the total number of characters in the given file
c) Count the total number of consonants in the given file
d) Check if the file contains any vowels

Correct answer is: c) Count the total number of consonants in the given file
Explanation: The given code opens a file named “file.txt” and reads its contents. It splits the content into individual words and assigns them to the `words` list. It then initializes a variable `count` to keep track of the number of consonants. Next, the code defines a list of vowels containing both lowercase and uppercase vowels. It then enters a nested loop structure where it iterates over each word in the `words` list and, for each word, iterates over each character in the word. Within the nested loop, it checks if the current character (`char`) is not present in the `vowels` list. If the character is not a vowel, it increments the `count` variable by 1. This process repeats for each character in each word. Finally, the code prints the value of `count`, which represents the total number of consonants present in the file.

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

				
					f1 = open('file.txt', 'r')
f2 = open('file2.txt', 'a')
lines = f1.readlines()
for line in lines:
    if 't' in line:
        f2.write(line)
f1.close()
f2.close()

				
			

a) It reads the contents of ‘file.txt’ and writes lines containing the letter ‘t’ to ‘file2.txt’.
b) It appends the contents of ‘file.txt’ to ‘file2.txt’.
c) It reads the contents of ‘file.txt’ and prints lines containing the letter ‘t’.
d) It creates a new file ‘file2.txt’ and writes lines containing the letter ‘t’ from ‘file.txt’.

Correct answer is: a) It reads the contents of ‘file.txt’ and writes lines containing the letter ‘t’ to ‘file2.txt’.
Explanation: The code opens two files, ‘file.txt’ in read mode (`’r’`) and ‘file2.txt’ in append mode (`’a’`). It then reads all the lines from ‘file.txt’ using `f1.readlines()`. The code then iterates over each line and checks if the letter ‘t’ is present in the line using the condition `if ‘t’ in line`. If the condition is true, the line is written to ‘file2.txt’ using `f2.write(line)`. Finally, the code closes both file objects using `f1.close()` and `f2.close()`.

Leave a Comment