Python Programming - Reading and Writing Files

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

32.
What is the purpose of the os.rename() function?
To remove a file
To rename a file or directory
To copy a file
To check if a file exists
Answer: Option
Explanation:
os.rename() is used to rename a file or directory in Python.

33.
How can you read and print only the lines that start with "Error:" from a log file named "logfile.txt"?
lines = open("logfile.txt").readlines()
for line in lines:
    if line.startswith("Error:"):
        print(line)
print_error_lines("logfile.txt")
with open("logfile.txt", "r") as file:
    print(file.read("Error:"))
with open("logfile.txt", "r") as file:
    for line in file:
        if "Error:" in line:
            print(line)
Answer: Option
Explanation:
Using startswith() to filter and print lines starting with "Error:".

34.
What is the purpose of the shutil.move() function?
To move a file or directory to a different location
To copy the contents of a file
To remove a file
To check if a file is empty
Answer: Option
Explanation:
shutil.move() is used to move a file or directory to a different location.

35.
How can you determine the number of lines in a file named "data.txt"?
lines = count_lines("data.txt")
print(lines)
with open("data.txt", "r") as file:
    lines = len(file.readlines())
    print(lines)
with open("data.txt", "r") as file:
    lines = file.linecount()
    print(lines)
if lines_exist("data.txt"):
    print(line_count("data.txt"))
Answer: Option
Explanation:
Using readlines() and len() to count the number of lines in the file.