9. Implementing real-time/technical applications using File handling. (copy from one file to another, word count, longest word)
#Python Program to copy the contents of one file into another
with open("test.txt") as f:
with open("out.txt", "w") as f1:
for line in f:
f1.write(line)
print("copied to out file :",line)
Word count
with open("test.txt") as f:
for line in f:
print("The original string is : " + line)
# using split() function
wordcount = len(line.split())
# total no of words
print ("The number of words in string are : " + str(wordcount))
Longest word
def longest_word(filename):
with open(filename, 'r') as infile:
words = infile.read().split()
max_len = len(max(words, key=len))
return word
for word in words:
if len(word) == max_len :
print(longest_word('test.txt'))
Comments
Post a Comment