Python Programming - Reading and Writing Files

Exercise : Reading and Writing Files - General Questions
  • Reading and Writing Files - General Questions
16.
What is the purpose of the os.remove() function?
To check if a file exists
To remove a directory
To delete a file
To rename a file
Answer: Option
Explanation:
The os.remove() function is used to delete a file in Python.

17.
How can you read and print only the even-numbered lines from a file named "numbers.txt"?
even_lines = open("numbers.txt").readlines()[1::2]
    for line in even_lines:
    print(line)
with open("numbers.txt", "r") as file:
    lines = file.readlines()
    for i in range(1, len(lines), 2):
        print(lines[i])
even_numbers("numbers.txt")
read_even("numbers.txt")
Answer: Option
Explanation:
Using list slicing to select even-numbered lines and then printing them.

18.
Which method is used to check if a file object is in a valid state?
validate()
check()
is_valid()
closed()
Answer: Option
Explanation:
The closed() method checks if a file object is in a valid state (closed or not).

19.
What is the purpose of the truncate() method when working with files?
To remove all contents of the file
To shorten the file name
To create a new file
To split the file into multiple parts
Answer: Option
Explanation:
The truncate() method is used to remove all contents of the file from the current position.

20.
How can you write a dictionary to a file named "data.json" in JSON format?
write_json("data.json", {"key": "value"})
json.write("data.json", {"key": "value"})
with open("data.json", "w") as file:
    json.dump({"key": "value"}, file)
file.write_json("data.json", {"key": "value"})
Answer: Option
Explanation:
Using json.dump() to write a dictionary to a JSON file.