Python File Handling Programs
Q1. Display the size of file 'book.txt' in bytes
import os
file_path = "book.txt"
if os.path.exists(file_path):
size = os.path.getsize(file_path)
print(f"Size of {file_path}: {size} bytes")
else:
print("File not found.")
Q2. Display the total number of lines in 'poem.txt'
with open("poem.txt", "r") as file:
lines = file.readlines()
print("Total number of lines:", len(lines))
Q3. Get roll no, name, class of 5 students and store in 'student.txt'
with open("student.txt", "w") as file:
for i in range(5):
roll = input("Enter Roll No: ")
name = input("Enter Name: ")
cls = input("Enter Class: ")
file.write(f"{roll}, {name}, {cls}\n")
Q4. Read 'Answer.txt' line by line, display each word separated by '#'
with open("Answer.txt", "r") as file:
for line in file:
words = line.strip().split()
print("#".join(words))
Q5. Count vowels and consonants in 'Result.txt'
vowels = "aeiouAEIOU"
vowel_count = consonant_count = 0
with open("Result.txt", "r") as file:
for ch in file.read():
if ch.isalpha():
if ch in vowels:
vowel_count += 1
else:
consonant_count += 1
print("Vowels:", vowel_count)
print("Consonants:", consonant_count)
Q6. Function to count words starting with 'a' or 'A' in 'STORY.TXT'
def DISPLAYWORDS():
count = 0
with open("STORY.TXT", "r") as file:
for word in file.read().split():
if word.lower().startswith('a'):
count += 1
print("Words starting with 'a' or 'A':", count)
DISPLAYWORDS()
Q7. Get employee info and write to 'emp.txt'
with open("emp.txt", "w") as file:
eno = input("Enter Employee No: ")
ename = input("Enter Employee Name: ")
eaddress = input("Enter Employee Address: ")
file.write(f"{eno}, {ename}, {eaddress}\n")
Q8. Read 'NOTE.txt' and display content in capital letters
with open("NOTE.txt", "r") as file:
content = file.read()
print(content.upper())
Q9. Print only digits from 'myfile.txt'
with open("myfile.txt", "r") as file:
content = file.read()
digits = ''.join([ch for ch in content if ch.isdigit()])
print("Digits in file:", digits)
Q10. Count vowels and consonants in 'alpha.txt'
vowels = "aeiouAEIOU"
vowel_count = consonant_count = 0
with open("alpha.txt", "r") as file:
for ch in file.read():
if ch.isalpha():
if ch in vowels:
vowel_count += 1
else:
consonant_count += 1
print("Vowels:", vowel_count)
print("Consonants:", consonant_count)
Q11. Display content of 'file1.txt' after removing leading/trailing spaces
with open("file1.txt", "r") as file:
content = file.read()
print(content.strip())