Exercise: Python

Questions for: Reading And Writing Files

How can you check if a file named "data.txt" exists in the current directory?
A:
if check_exists("data.txt"):
B:
if file.exists("data.txt"):
C:
if os.path.isfile("data.txt"):
D:
if is_file("data.txt"):
Answer: C
Using os.path.isfile() to check if the path refers to a regular file.
What does the file.readline() method do?
A:
Reads the entire file content
B:
Reads a specific line from the file
C:
Reads the last line of the file
D:
Reads the next line from the file
Answer: D
file.readline() reads the next line from the file.
How can you append the text "Additional content" to an existing file named "existing.txt"?
A:
with open("existing.txt", "a") as file:
    file.write("Additional content")
B:
append_text("existing.txt", "Additional content")
C:
with open("existing.txt", "w") as file:
    file.append("Additional content")
D:
with open("existing.txt", "a") as file:
    file.append("Additional content")
Answer: A
Using open() in append mode to add content to an existing file.
How can you copy the contents of a file named "source.txt" to another file named "destination.txt" while preserving the original file's metadata?
A:
shutil.copy("source.txt", "destination.txt")
B:
copy_with_metadata("source.txt", "destination.txt")
C:
with open("destination.txt", "w") as dest:
    dest.write(open("source.txt").read())
    os.utime("destination.txt", os.path.getatime("source.txt"), os.path.getmtime("source.txt"))
D:
duplicate_file("source.txt", "destination.txt")
Answer: A
Using shutil.copy() to copy the file contents and preserve metadata.
How can you read and print the lines containing only alphabetic characters from a file named "textfile.txt"?
A:
with open("textfile.txt", "r") as file:
    lines = file.readlines()
    for line in lines:
        if line.isalpha():
            print(line)
B:
print_alpha_lines("textfile.txt")
C:
with open("textfile.txt", "r") as file:
    print(file.read("[a-zA-Z]"))
D:
with open("textfile.txt", "r") as file:
    for line in file:
        if line.isalphabetic():
            print(line)
Answer: A
Using line.isalpha() to check if the line contains only alphabetic characters.
Ad Slot (Above Pagination)
Quiz