Exercise: Reading And Writing Files
Questions for: Reading And Writing Files
How can you create a new directory named "data_folder" in the current working directory?
A:
os.mkdir("data_folder")
B:
create_directory("data_folder")
C:
shutil.new_dir("data_folder")
D:
os.create_folder("data_folder")
Answer: A
Using
os.mkdir() to create a new directory.
How can you read and print the lines containing the word "error" from a log file named "logfile.txt"?
A:
with open("logfile.txt", "r") as file:
lines = file.readlines()
for line in lines:
if "error" in line.lower():
print(line)
B:
print_error_lines("logfile.txt")
C:
with open("logfile.txt", "r") as file:
print(file.read("error"))
D:
with open("logfile.txt", "r") as file:
for line in file:
if "error".casefold() in line:
print(line)
Answer: A
Using
line.lower() to make the comparison case-insensitive.Discuss About this Question.
What does the
file.writelines(lines) method do?
A:
Writes a single line to the file
B:
Writes multiple lines to the file from a list
C:
Writes the entire content of another file
D:
Writes a specific number of characters to the file
Answer: B
file.writelines(lines) writes multiple lines to the file from a list.Discuss About this Question.
How can you read and print the first word from each line in a file named "text.txt"?
A:
with open("text.txt", "r") as file:
for line in file:
print(line.split()[0])
B:
print_first_words("text.txt")
C:
with open("text.txt", "r") as file:
print(file.readline().split()[0])
D:
with open("text.txt", "r") as file:
print(file.read(1).split()[0])
Answer: A
Using
line.split()[0] to get the first word from each line.Discuss About this Question.
How can you copy the contents of a text file named "source.txt" to another text file named "destination.txt"?
A:
with open("source.txt", "r") as source, open("destination.txt", "w") as dest:
dest.write(source.read())
B:
copy_text_file("source.txt", "destination.txt")
C:
shutil.copyfile("source.txt", "destination.txt")
D:
duplicate_content("source.txt", "destination.txt")
Answer: A
Using
with statement to open both files and copy the content.Discuss About this Question.
Ad Slot (Above Pagination)
Discuss About this Question.