Python Programming - Reading and Writing Files

Exercise : Reading and Writing Files - General Questions
  • Reading and Writing Files - General Questions
86.
How can you read and print the first 5 characters from a file named "sample.txt"?
with open("sample.txt", "r") as file:
    print(file.read(5))
print_first_characters("sample.txt", 5)
with open("sample.txt", "r") as file:
    print(file.readline(5))
with open("sample.txt", "r") as file:
    print(file.read(1, 5))
Answer: Option
Explanation:
Using file.read(5) to read the first 5 characters.

87.
What does the os.path.abspath() function do?
Returns the absolute path of the current working directory
Returns the relative path of the specified file
Returns the absolute path of the specified file
Checks if a file exists in the current directory
Answer: Option
Explanation:
os.path.abspath() returns the absolute path of the current working directory.

88.
How can you write a list of strings to a text file named "output.txt" in Python, with each string on a new line?
with open("output.txt", "w") as file:
    strings = ["Hello", "World", "Python"]
    file.write("\n".join(strings))
write_lines("output.txt", ["Hello", "World", "Python"])
text.write("output.txt", ["Hello", "World", "Python"])
with open("output.txt", "w") as file:
    file.writelines(["Hello", "World", "Python"])
Answer: Option
Explanation:
Using "\n".join(strings) to join the strings with newline characters.

89.
What does the shutil.rmtree() function do?
Removes a file
Removes a directory and its contents
Renames a directory
Copies a directory and its contents
Answer: Option
Explanation:
shutil.rmtree() removes a directory and its contents.

90.
What does the file.writelines() method do?
Writes a single line to the file
Writes multiple lines to the file from a list
Writes the entire content of another file
Writes a specific number of characters to the file
Answer: Option
Explanation:
file.writelines() writes multiple lines to the file from a list.