File Handling (Programs)
File Handling (Programs)
Q1. Read a text file line by line an display each word separated by a
‘#’ .
def read_words():
f = open("file2.txt", 'r')
lines = f.readlines()
for line in lines:
words = line.split()
for word in words:
print(word + "#", end = "")
print()
f.close()
def run():
f = open('file2.txt', 'w')
f.write("This is the new file.")
f.write("\nQuestions are solved!")
f.close()
read_words()
run()
OUTPUT :
This#is#the#new#file.#
Questions#are#solved!#
Q2. Read a text file and display the number of vowels/ consonants/
uppercase/ lowercase characters in the file.
def count_characters(filename):
vowels_count = 0
consonants_count = 0
uppercase_count = 0
lowercase_count = 0
vowels = list("aeiouAEIOU")
try:
with open(filename, 'r')as file:
for line in file:
for char in line:
if char.isalpha():
if char in vowels:
vowels_count+=1
else:
consonants_count+=1
if char.isupper():
uppercase_count+=1
elif char.islower():
lowercase_count+=1
except FileNotFoundError:
print(f"The file'{filename}'does not exist.")
return
except Exception as e:
print(f"An error occured:{e}")
return
print(f"Vowels:{vowels_count}")
print(f"Consonants:{consonants_count}")
print(f"Uppercase characters:{uppercase_count}")
print(f"Lowercase characters:{lowercase_count}")
def run():
f = open('file2.txt', 'w')
f.write("This is the new file.")
f.write("\nQuestions are solved!")
f.close()
x = "file2.txt"
count_characters(x)
run()
OUTPUT :
Vowels:14
Consonants:20
Uppercase characters:2
Lowercase characters:32
Q3. Remove all lines that contain the character ’a’ I a file and write it to another file.
def remove_lines_with_a(input_filename, output_filename):
infile = open(input_filename, 'r')
outfile = open(output_filename,'w')
lines = infile.readlines()
for line in lines :
if 'a' not in line:
outfile.write(line)
infile.close()
outfile.close()
def run():
f = open('file1.txt', 'w')
f.write("This is the new file.")
f.write("\nQuestions are solved!")
f.write("\nPython is fun.")
f.close()
x = "file1.txt"
y = "file2.txt"
remove_lines_with_a(x, y)
run()
OUTPUT :
Lines without 'a' have been written to'file2.txt'.
This is the new file.
Python is fun.
Q4. Creat a binary file with nme,roll