Python Programming - Reading and Writing Files

Exercise : Reading and Writing Files - General Questions
  • Reading and Writing Files - General Questions
36.
What is the purpose of the os.path.isdir() function?
Checks if a file exists
Checks if a path is a regular file
Checks if a path points to a directory
Checks if a file is empty
Answer: Option
Explanation:
os.path.isdir() checks if a path points to a directory.

37.
How can you write a list of dictionaries to a CSV file named "data.csv"?
write_csv("data.csv", [{"key1": "value1"}, {"key2": "value2"}])
with open("data.csv", "w") as file:
    write_csv(file, [{"key1": "value1"}, {"key2": "value2"}])
csv.write("data.csv", [{"key1": "value1"}, {"key2": "value2"}])
with open("data.csv", "w") as file:
    csv.writer(file).writerow([{"key1", "value1"}, {"key2", "value2"}])
Answer: Option
Explanation:
Using a context manager to open the file and writing a list of dictionaries to a CSV file.

38.
What does the file.tell() method return?
Returns the file's absolute path
Returns the size of a file in bytes
Returns the current position of the file cursor
Returns the file's creation time
Answer: Option
Explanation:
The tell() method returns the current position of the file cursor.

39.
How can you create a new directory named "my_directory"?
os.newdir("my_directory")
os.create_dir("my_directory")
os.mkdir("my_directory")
new_directory("my_directory")
Answer: Option
Explanation:
The os.mkdir() function is used to create a new directory in Python.

40.
How can you read and print the lines containing numbers from a file named "text.txt"?
lines = open("text.txt").readlines()
for line in lines:
    if any(char.isdigit() for char in line):
        print(line)
read_numeric_lines("text.txt")
with open("text.txt", "r") as file:
    print(file.read("\d+"))
with open("text.txt", "r") as file:
    for line in file:
        if line.isdigit():
            print(line)
Answer: Option
Explanation:
Using any() and isdigit() to filter and print lines containing numbers.