Python Programming - Reading and Writing Files - Discussion

Discussion Forum : Reading and Writing Files - General Questions (Q.No. 13)
13.
How can you read and print the first 3 lines of a file named "sample.txt"?
lines = open("sample.txt").readlines()[:3]
    for line in lines:
    print(line)
with open("sample.txt", "r") as file:
    for i in range(3):
        print(file.readline())
contents = read_lines("sample.txt", 3)
print(contents)
first_three_lines("sample.txt")
Answer: Option
Explanation:
Using a for loop with readline() to read and print the first 3 lines.
Discussion:
Be the first person to comment on this question !

Post your comments here:

Your comments will be displayed after verification.