Python Programming - Reading and Writing Files

Exercise : Reading and Writing Files - General Questions
  • Reading and Writing Files - General Questions
76.
What does the file.encoding attribute represent?
Represents the file's access mode
Represents the file's size in bytes
Represents the file's encoding (character set)
Represents the file's creation time
Answer: Option
Explanation:
file.encoding represents the file's encoding.

77.
How can you read and print the lines containing the word "success" or "failure" from a log file named "logfile.txt"?
with open("logfile.txt", "r") as file:
    lines = file.readlines()
    for line in lines:
        if "success" in line.lower() or "failure" in line.lower():
            print(line)
print_log_lines("logfile.txt", ["success", "failure"])
with open("logfile.txt", "r") as file:
    print(file.read("success" or "failure"))
with open("logfile.txt", "r") as file:
    for line in file:
        if "success".casefold() in line or "failure".casefold() in line:
            print(line)
Answer: Option
Explanation:
Using line.lower() to make the comparison case-insensitive.

78.
What does the file.fileno() method return?
Returns the file's size in bytes
Returns the file's access mode
Returns the file's file descriptor
Returns the file's encoding
Answer: Option
Explanation:
file.fileno() returns the file's file descriptor.

79.
How can you read and print the lines containing only alphabetic characters from a file named "textfile.txt"?
with open("textfile.txt", "r") as file:
    lines = file.readlines()
    for line in lines:
        if line.isalpha():
            print(line)
print_alpha_lines("textfile.txt")
with open("textfile.txt", "r") as file:
    print(file.read("[a-zA-Z]"))
with open("textfile.txt", "r") as file:
    for line in file:
        if line.isalphabetic():
            print(line)
Answer: Option
Explanation:
Using line.isalpha() to check if the line contains only alphabetic characters.

80.
How can you copy the contents of a file named "source.txt" to another file named "destination.txt" while preserving the original file's metadata?
shutil.copy("source.txt", "destination.txt")
copy_with_metadata("source.txt", "destination.txt")
with open("destination.txt", "w") as dest:
    dest.write(open("source.txt").read())
    os.utime("destination.txt", os.path.getatime("source.txt"), os.path.getmtime("source.txt"))
duplicate_file("source.txt", "destination.txt")
Answer: Option
Explanation:
Using shutil.copy() to copy the file contents and preserve metadata.