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.
with open("sample.txt", "r") as file:
lines = file.readlines()
with open("sample.txt", "w") as file:
for line in lines:
file.write(line.strip() + "\n")
Write a Python program to copy the contents of one file into another.
with open("file1.txt", "r") as file1:
with open("file2.txt", "w") as file2:
file2.write(file1.read())
Write a Python program to find the longest word in a file.
with open("sample.txt", "r") as file:
words = file.read().split()
longest_word = max(words, key=len)
print("Longest word in file:", longest_word)
Last updated