Exercise: Python

Questions for: Reading And Writing Files

How can you read and print the lines that end with "!" from a file named "text.txt"?
A:
with open("text.txt", "r") as file:
    lines = file.readlines()
    for line in lines:
        if line.endswith("!"):
            print(line)
B:
print_lines_with_end("text.txt", "!")
C:
with open("text.txt", "r") as file:
    print(file.read("!"))
D:
lines = open("text.txt").readlines()
for line in lines:
    if line.end() == "!":
        print(line)
Answer: A
Using endswith() to filter and print lines ending with "!".
How can you check if a file named "config.ini" exists?
A:
if isfile("config.ini"):
B:
if exists("config.ini"):
C:
if file_exists("config.ini"):
D:
if os.path.file_exists("config.ini"):
Answer: B
Using exists() to check if a file exists.
How can you copy a file named "source.txt" to a new location and rename it as "destination.txt"?
A:
copy_file("source.txt", "destination.txt")
B:
shutil.copy("source.txt", "destination.txt")
C:
with open("destination.txt", "w") as dest:
    dest.write(open("source.txt").read())
D:
rename_file("source.txt", "destination.txt")
Answer: B
Using shutil.copy() to copy and rename a file.
What does the shutil.rmtree() function do?
A:
Removes a file
B:
Removes a directory and its contents
C:
Renames a file
D:
Copies a directory
Answer: B
shutil.rmtree() removes a directory and its contents recursively.
How can you read and print only the lines longer than 20 characters from a file named "data.txt"?
A:
with open("data.txt", "r") as file:
    lines = file.readlines()
    for line in lines:
        if len(line) > 20:
            print(line)
B:
print_long_lines("data.txt", 20)
C:
with open("data.txt", "r") as file:
    print(file.read(20))
D:
lines = open("data.txt").readlines()
for line in lines:
    if line.length() > 20:
        print(line)
Answer: A
Using len() to filter and print lines longer than 20 characters.
Ad Slot (Above Pagination)
Quiz