Python Programming - Reading and Writing Files

Exercise : Reading and Writing Files - General Questions
  • Reading and Writing Files - General Questions
56.
What does the os.path.join() function do?
Joins two paths into a single path
Checks if a path is a regular file
Returns the base name of a file or directory
Moves a file to a different directory
Answer: Option
Explanation:
os.path.join() joins two paths into a single path.

57.
How can you read and print the lines with odd line numbers from a file named "numbers.txt"?
with open("numbers.txt", "r") as file:
    lines = file.readlines()
    for i in range(len(lines)):
        if i % 2 != 0:
            print(lines[i])
print_odd_lines("numbers.txt")
with open("numbers.txt", "r") as file:
    print(file.read(2))
with open("numbers.txt", "r") as file:
    for line in file:
        if line.number() % 2 != 0:
            print(line)
Answer: Option
Explanation:
Using the index to identify odd line numbers and printing corresponding lines.

58.
What is the purpose of the file.truncate() method?
Closes the file
Truncates the file at the current position
Reads the file content
Writes the buffered data to the file
Answer: Option
Explanation:
file.truncate() truncates the file at the current position.

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

60.
How can you remove a file named "data.txt"?
remove_file("data.txt")
os.remove("data.txt")
delete_file("data.txt")
file.delete("data.txt")
Answer: Option
Explanation:
Using os.remove() to remove a file in Python.