Python Programming - Reading and Writing Files

Exercise : Reading and Writing Files - General Questions
  • Reading and Writing Files - General Questions
26.
How can you append the string "new content" to an existing file named "existing_file.txt"?
open("existing_file.txt", "a").write("new content")
open("existing_file.txt", "w").write("new content")
append_content("existing_file.txt", "new content")
with open("existing_file.txt", "a") as file:
    file.append("new content")
Answer: Option
Explanation:
The mode "a" in open() is used for appending content to an existing file.

27.
What does the os.path.getsize() function return?
Returns the creation time of a file
Returns the file extension
Returns the size of a file in bytes
Returns the number of lines in a file
Answer: Option
Explanation:
os.path.getsize() returns the size of a file in bytes.

28.
How can you read and print the last 5 lines from a file named "log.txt"?
with open("log.txt", "r") as file:
    lines = file.readlines()
    for line in lines[-5:]:
        print(line)
last_five_lines("log.txt")
with open("log.txt", "r") as file:
    print(file.read()[-5:])
lines = open("log.txt").readlines()[-5:]
for line in lines:
    print(line)
Answer: Option
Explanation:
Using readlines() and list slicing to get the last 5 lines.

29.
What is the purpose of the os.path.abspath() function?
Returns the file's absolute path
Returns the file's relative path
Returns the file's base name
Returns the file's directory name
Answer: Option
Explanation:
os.path.abspath() returns the absolute path of a file.

30.
How can you check if a file named "data.csv" is empty?
if not is_empty("data.csv"):
if get_size("data.csv") == 0:
if file_empty("data.csv"):
if os.path.getsize("data.csv") == 0:
Answer: Option
Explanation:
Using os.path.getsize() to check if the file size is 0, indicating an empty file.