Exercise: Reading And Writing Files

Questions for: Reading And Writing Files

How can you append the string "new content" to an existing file named "existing_file.txt"?
A:
open("existing_file.txt", "a").write("new content")
B:
open("existing_file.txt", "w").write("new content")
C:
append_content("existing_file.txt", "new content")
D:
with open("existing_file.txt", "a") as file:
    file.append("new content")
Answer: A
The mode "a" in open() is used for appending content to an existing file.
What does the os.path.isfile() function check?
A:
Checks if a path exists
B:
Checks if a file is a binary file
C:
Checks if a file is empty
D:
Checks if a path points to a regular file
Answer: D
os.path.isfile() checks if a path points to a regular file (not a directory).
How can you read and print only the lines containing the word "Python" from a file named "text.txt"?
A:
lines = open("text.txt").readlines()
    for line in lines:
    if "Python" in line:
        print(line)
B:
with open("text.txt", "r") as file:
    for line in file:
        if "Python" in line:
            print(line)
C:
print_python_lines("text.txt")
D:
with open("text.txt", "r") as file:
    print(file.read("Python"))
Answer: B
Using a for loop to iterate through the lines and printing lines containing "Python".
What is the purpose of the shutil.copy() function?
A:
To move a file
B:
To copy the contents of a file
C:
To create a new file
D:
To remove a file
Answer: B
shutil.copy() is used to copy the contents of a file to another location.
How can you read the content of a binary file named "binary_data.dat"?
A:
content = open("binary_data.dat").read()
B:
content = open("binary_data.dat", "rb").read()
C:
content = read_binary("binary_data.dat")
D:
content = open_binary("binary_data.dat").read()
Answer: B
To read the content of a binary file, the file should be opened with mode "rb".
Ad Slot (Above Pagination)
Quiz