Python Programming - Reading and Writing Files

Exercise : Reading and Writing Files - General Questions
  • Reading and Writing Files - General Questions
96.
What does the file.is_closed attribute check for?
Checks if the file is open for reading
Checks if the file is a binary file
Checks if the file is a text file
Checks if the file is closed
Answer: Option
Explanation:
file.is_closed checks if the file is closed.

97.
How can you read and print the contents of a binary file named "binary.dat"?
with open("binary.dat", "rb") as file:
    print(file.read())
print_binary_content("binary.dat")
with open("binary.dat", "r") as file:
    print(file.read())
with open("binary.dat", "rb") as file:
    print(file.readlines())
Answer: Option
Explanation:
Using open() in binary read mode to read and print the binary content.

98.
How can you copy the contents of a text file named "source.txt" to another text file named "destination.txt"?
with open("source.txt", "r") as source, open("destination.txt", "w") as dest:
    dest.write(source.read())
copy_text_file("source.txt", "destination.txt")
shutil.copyfile("source.txt", "destination.txt")
duplicate_content("source.txt", "destination.txt")
Answer: Option
Explanation:
Using with statement to open both files and copy the content.

99.
What does the file.tell() method return?
Returns the file's access mode
Returns the file's size in bytes
Returns the file's file descriptor
Returns the current file cursor position
Answer: Option
Explanation:
file.tell() returns the current file cursor position.

100.
How can you read and print the first word from each line in a file named "text.txt"?
with open("text.txt", "r") as file:
    for line in file:
        print(line.split()[0])
print_first_words("text.txt")
with open("text.txt", "r") as file:
    print(file.readline().split()[0])
with open("text.txt", "r") as file:
    print(file.read(1).split()[0])
Answer: Option
Explanation:
Using line.split()[0] to get the first word from each line.