File Handling Assignments
Write a Python program to read a file line by line and print its contents.
file = open("sample.txt", "r")
for line in file:
print(line)
file.close()Write a Python program to count the number of lines in a file.
file = open("sample.txt", "r")
count = 0
for line in file:
count += 1
print("Number of lines in file:", count)
file.close()Write a Python program to append text to an existing file.
file = open("sample.txt", "a")
file.write("This text will be appended to the end of the file.\n")
file.close()Write a Python program to read the last n lines of a file.
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))Write a Python program to remove the newline character from the end of each line in a file.
Write a Python program to copy the contents of one file into another.
Write a Python program to find the longest word in a file.
Last updated