# File Handling - Practice Problems:
# 1. Read File:
with open("example.txt", "r") as file:
content = file.read()
print(content)
# 2. Write to File:
list = ["apple", "banana", "cherry"]
string = " ".join(list)
words = string.split()
with open("fileio.txt", "w") as file:
for i in words:
file.write(i + "\n")
# 3. Word Count from File:
with open("example.txt", "r") as file:
content = file.read()
words = content.split()
list = list(words)
result = len(list)
print(f"The number of words in the file are {result}")
# 4. Line Count:
with open("example.txt", "r") as file:
content = file.read()
words = content.split("\n")
list = list(words)
result = len(list)
print(f"The number of lines in the file are {result}")
# 5. Find Specific Word:
with open("example.txt", "r") as file:
content = file.read()
words = content.split()
list = list(words)
if "Hello" in list:
print("Hello is present in the file")
else:
print("Hello is absent in the file")
# 6. Copy File:
def copyfile(sourcefile, destinationfile):
with open(sourcefile, "r") as source:
content = source.read()
with open(destinationfile, "w") as destination:
destination.write(content)
copyfile("example.txt", "fileio.txt")
# 7. Append to File:
def append(sourcefile):
with open(sourcefile, "a") as file:
file.write("\nI am happy")
append("fileio.txt")
# 8. Replace Word in File:
with open("fileio.txt", "r") as file:
content = file.read()
modified = content.replace("This", "Hello")
with open("fileio.txt", "w") as file:
file.write(modified)
# 9. Remove Blank Lines:
with open("file.txt", "r") as file:
content = file.read()
words = content.split()
string = "".join(words)
with open("file.txt", "w") as file:
file.write(string)
# 10. File Summary:
def summary(source):
with open(source, "r") as file:
content = file.read()
words = content.split("\n")
list1 = list(words)
result = len(list1)
print(f"The number of lines in the file are {result}")
with open(source, "r") as file:
content = file.read()
words = content.split()
list1 = list(words)
result = len(list1)
print(f"The number of words in the file are {result}")
with open(source, "r") as file:
count = 0
content = file.read()
words = content.split()
string = "".join(words)
for i in string:
count += 1
print(f"The number of characters in the file are {count}")
summary("example.txt")