Python Assignments
  • Python Assignments
  • Operators Assignment
  • User Input Assignments
  • String Assignments
  • Conditional Statements - Assignments
  • Loops - Assignments
  • List Assignments
  • Function Practice Questions
  • File Handling Assignments
  • Miscellaneous Python Assignments
Powered by GitBook
On this page

File Handling Assignments

  1. 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()
  1. 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()
  1. 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()
  1. 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))
  1. 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")
  1. 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())
  1. 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)
PreviousFunction Practice QuestionsNextMiscellaneous Python Assignments

Last updated 2 years ago