Python Programming - Reading and Writing Files

Exercise : Reading and Writing Files - General Questions
  • Reading and Writing Files - General Questions
46.
How can you read and print the lines that end with "!" from a file named "text.txt"?
with open("text.txt", "r") as file:
    lines = file.readlines()
    for line in lines:
        if line.endswith("!"):
            print(line)
print_lines_with_end("text.txt", "!")
with open("text.txt", "r") as file:
    print(file.read("!"))
lines = open("text.txt").readlines()
for line in lines:
    if line.end() == "!":
        print(line)
Answer: Option
Explanation:
Using endswith() to filter and print lines ending with "!".

47.
What does the os.path.getctime() function return?
Returns the file's creation time
Returns the file's size in bytes
Returns the file's absolute path
Returns the file's modification time
Answer: Option
Explanation:
os.path.getctime() returns the creation time of a file.

48.
How can you write a list of strings to a file named "output.txt"?
write_list("output.txt", ["string1", "string2"])
with open("output.txt", "w") as file:
    write_lines(file, ["string1", "string2"])
file.write_strings("output.txt", ["string1", "string2"])
with open("output.txt", "w") as file:
    file.write(["string1", "string2"])
Answer: Option
Explanation:
Using a context manager to open the file and writing a list of strings.

49.
How can you check if a file named "data.xml" is a valid XML file?
if is_valid_xml("data.xml"):
if is_xml_file("data.xml"):
if validate_xml("data.xml"):
if os.path.isxml("data.xml"):
Answer: Option
Explanation:
Checking if a file has an XML extension to determine if it's a valid XML file.

50.
How can you read and print the lines containing both "Python" and "programming" from a file named "code.txt"?
with open("code.txt", "r") as file:
    lines = file.readlines()
    for line in lines:
        if "Python" in line and "programming" in line:
            print(line)
print_python_programming_lines("code.txt")
with open("code.txt", "r") as file:
    print(file.read("Python programming"))
with open("code.txt", "r") as file:
    for line in file:
        if "Python" in line:
            print(line)
        elif "programming" in line:
            print(line)
Answer: Option
Explanation:
Using in to check for both "Python" and "programming" in each line.