#GRADE 12 - PRACTICAL 8 - TEXT FILES """WAP to perform the following operations on ‘ Song.txt’
i) Accept a song(until stop is entered ) & write to the file. Display the file.
ii)Display alternate lines of the file. Also display the number of uppercase & lowercase characters in the file.
iii) Copy all the words starting with ‘a’,'b','c','d' or ‘e’(any case ) into 'abcde.txt’.Display ‘abcde.txt’
iv) Copy all the lines containing the word ‘you’ into a file named ‘you.txt’ after changing it to YOU.
NOTE : Ensure no error is thrown if a non existent file is being read"""
def create():
f = open("Song.txt", "w")
while True:
line = input("Enter line: ")
if line.lower()=='stop':
break
f.write(line + "\n")
f.close()
print("Song written to file successfully.")
with open("Song.txt", "r") as f:
print(f.read())
def display():
try:
f = open("Song.txt", "r")
data = f.read()
print("\n of the file:")
lines=data.splitlines()
for line in lines[::2]:
print(line)
upper = 0
lower = 0
for ch in data:
if ch.isupper():
upper += 1
elif ch.islower():
lower += 1
print("Uppercase characters:", upper)
print("Lowercase characters:", lower)
f.close()
except FileNotFoundError:
print('Sorry , song file is not found ')
except exception as e:
print('Unexpected error : ',e)
while True:
print("\nMENU")
print("1. Write song to file")
print("2. Display file and count uppercase & lowercase characters")
print("3. Copy words starting with a/b/c/d/e into abcde.txt")
print("4. Copy lines containing 'you' into you.txt (change to YOU)")
print("5. Exit")
ch = int(input("Enter your choice: "))
if ch == 1:
create()
elif ch == 2:
display()
elif ch == 3:
abcde()
elif ch == 4:
you_lines()
elif ch == 5:
break
else:
print("Invalid choice")