Exercise: Reading And Writing Files

Questions for: Reading And Writing Files

What is the purpose of the os.path.isdir() function?
A:
Checks if a file exists
B:
Checks if a path is a regular file
C:
Checks if a path points to a directory
D:
Checks if a file is empty
Answer: C
os.path.isdir() checks if a path points to a directory.
How can you determine the number of lines in a file named "data.txt"?
A:
lines = count_lines("data.txt")
print(lines)
B:
with open("data.txt", "r") as file:
    lines = len(file.readlines())
    print(lines)
C:
with open("data.txt", "r") as file:
    lines = file.linecount()
    print(lines)
D:
if lines_exist("data.txt"):
    print(line_count("data.txt"))
Answer: B
Using readlines() and len() to count the number of lines in the file.
What is the purpose of the shutil.move() function?
A:
To move a file or directory to a different location
B:
To copy the contents of a file
C:
To remove a file
D:
To check if a file is empty
Answer: A
shutil.move() is used to move a file or directory to a different location.
How can you read and print only the lines that start with "Error:" from a log file named "logfile.txt"?
A:
lines = open("logfile.txt").readlines()
for line in lines:
    if line.startswith("Error:"):
        print(line)
B:
print_error_lines("logfile.txt")
C:
with open("logfile.txt", "r") as file:
    print(file.read("Error:"))
D:
with open("logfile.txt", "r") as file:
    for line in file:
        if "Error:" in line:
            print(line)
Answer: A
Using startswith() to filter and print lines starting with "Error:".
What is the purpose of the os.rename() function?
A:
To remove a file
B:
To rename a file or directory
C:
To copy a file
D:
To check if a file exists
Answer: B
os.rename() is used to rename a file or directory in Python.
Ad Slot (Above Pagination)
Quiz