Exercise: Python

Questions for: Reading And Writing Files

How can you read and print the first 10 characters from a file named "sample.txt"?
A:
with open("sample.txt", "r") as file:
    print(file.read(10))
B:
first_ten_chars("sample.txt")
C:
with open("sample.txt", "r") as file:
    print(file.readline(10))
D:
chars = open("sample.txt").read(10)
print(chars)
Answer: A
Using read(10) to read and print the first 10 characters of the file.
How can you check if a file named "data.csv" is empty?
A:
if not is_empty("data.csv"):
B:
if get_size("data.csv") == 0:
C:
if file_empty("data.csv"):
D:
if os.path.getsize("data.csv") == 0:
Answer: D
Using os.path.getsize() to check if the file size is 0, indicating an empty file.
What is the purpose of the os.path.abspath() function?
A:
Returns the file's absolute path
B:
Returns the file's relative path
C:
Returns the file's base name
D:
Returns the file's directory name
Answer: A
os.path.abspath() returns the absolute path of a file.
How can you read and print the last 5 lines from a file named "log.txt"?
A:
with open("log.txt", "r") as file:
    lines = file.readlines()
    for line in lines[-5:]:
        print(line)
B:
last_five_lines("log.txt")
C:
with open("log.txt", "r") as file:
    print(file.read()[-5:])
D:
lines = open("log.txt").readlines()[-5:]
for line in lines:
    print(line)
Answer: A
Using readlines() and list slicing to get the last 5 lines.
What does the os.path.getsize() function return?
A:
Returns the creation time of a file
B:
Returns the file extension
C:
Returns the size of a file in bytes
D:
Returns the number of lines in a file
Answer: C
os.path.getsize() returns the size of a file in bytes.
Ad Slot (Above Pagination)
Quiz