File Handling Assignments
file = open("sample.txt", "r")
for line in file:
print(line)
file.close()file = open("sample.txt", "r")
count = 0
for line in file:
count += 1
print("Number of lines in file:", count)
file.close()file = open("sample.txt", "a")
file.write("This text will be appended to the end of the file.\n")
file.close()def read_last_n_lines(file_name, n):
with open(file_name, "r") as file:
lines = file.readlines()
return "".join(lines[-n:])
print(read_last_n_lines("sample.txt", 3))Last updated