Exercise: Reading And Writing Files

Questions for: Reading And Writing Files

What is the purpose of the os.path.basename() function?
A:
Returns the base name of a file or directory
B:
Returns the absolute path of a file
C:
Checks if a path is a regular file
D:
Deletes a file
Answer: A
os.path.basename() returns the base name of a file or directory.
How can you read and print the lines containing numbers from a file named "text.txt"?
A:
lines = open("text.txt").readlines()
for line in lines:
    if any(char.isdigit() for char in line):
        print(line)
B:
read_numeric_lines("text.txt")
C:
with open("text.txt", "r") as file:
    print(file.read("\d+"))
D:
with open("text.txt", "r") as file:
    for line in file:
        if line.isdigit():
            print(line)
Answer: A
Using any() and isdigit() to filter and print lines containing numbers.
How can you create a new directory named "my_directory"?
A:
os.newdir("my_directory")
B:
os.create_dir("my_directory")
C:
os.mkdir("my_directory")
D:
new_directory("my_directory")
Answer: C
The os.mkdir() function is used to create a new directory in Python.
What does the file.tell() method return?
A:
Returns the file's absolute path
B:
Returns the size of a file in bytes
C:
Returns the current position of the file cursor
D:
Returns the file's creation time
Answer: C
The tell() method returns the current position of the file cursor.
How can you write a list of dictionaries to a CSV file named "data.csv"?
A:
write_csv("data.csv", [{"key1": "value1"}, {"key2": "value2"}])
B:
with open("data.csv", "w") as file:
    write_csv(file, [{"key1": "value1"}, {"key2": "value2"}])
C:
csv.write("data.csv", [{"key1": "value1"}, {"key2": "value2"}])
D:
with open("data.csv", "w") as file:
    csv.writer(file).writerow([{"key1", "value1"}, {"key2", "value2"}])
Answer: B
Using a context manager to open the file and writing a list of dictionaries to a CSV file.
Ad Slot (Above Pagination)
Quiz