Python Programming - Reading and Writing Files

Exercise : Reading and Writing Files - General Questions
  • Reading and Writing Files - General Questions
61.
What does the file.seek() method do?
Closes the file
Moves the file cursor to a specified position
Reads the file content
Truncates the file at the current position
Answer: Option
Explanation:
file.seek() moves the file cursor to a specified position.

62.
How can you read and print the last 10 lines from a file named "log.txt"?
with open("log.txt", "r") as file:
    lines = file.readlines()
    for line in lines[-10:]:
        print(line)
print_last_lines("log.txt", 10)
with open("log.txt", "r") as file:
    print(file.tail(10))
with open("log.txt", "r") as file:
    for line in file:
        if line.number() > len(file) - 10:
            print(line)
Answer: Option
Explanation:
Using list slicing to get the last 10 lines and printing them.

63.
What is the purpose of the file.writelines() method?
Writes a list of strings to a file
Writes the buffered data to the file
Writes a list of dictionaries to a file
Writes a list of numbers to a file
Answer: Option
Explanation:
file.writelines() writes a list of strings to a file.

64.
How can you create a new text file named "new_file.txt" and write the text "Hello, World!" to it?
new_file("new_file.txt", "Hello, World!")
with open("new_file.txt", "w") as file:
    write_text(file, "Hello, World!")
text.write("new_file.txt", "Hello, World!")
with open("new_file.txt", "w") as file:
    file.write("Hello, World!")
Answer: Option
Explanation:
Using a context manager to open the file and writing the text to it.

65.
How can you check if a file named "data.csv" is a valid CSV file?
if is_valid_csv("data.csv"):
if is_csv_file("data.csv"):
if validate_csv("data.csv"):
if os.path.iscsv("data.csv"):
Answer: Option
Explanation:
Checking if a file has a CSV extension to determine if it's a valid CSV file.