20 Python Programs on Text File Handling
1. Create and write a text file
f = open("[Link]", "w")
[Link]("Hello, this is a text file.")
[Link]()
2. Read a text file
f = open("[Link]", "r")
print([Link]())
[Link]()
3. Append text to a file
f = open("[Link]", "a")
[Link]("\nThis is an appended line.")
[Link]()
4. Read file line by line
f = open("[Link]", "r")
for line in f:
print([Link]())
[Link]()
5. Count the number of lines in a file
f = open("[Link]", "r")
count = 0
for line in f:
count += 1
print("Total lines:", count)
[Link]()
6. Count number of words in a file
f = open("[Link]", "r")
words = [Link]().split()
print("Total words:", len(words))
[Link]()
7. Count number of characters in a file
f = open("[Link]", "r")
data = [Link]()
print("Total characters:", len(data))
[Link]()
8. Count occurrence of a specific word
f = open("[Link]", "r")
data = [Link]()
word = "text"
count = [Link](word)
print(f"'{word}' occurs {count} times")
[Link]()
9. Find the longest word in a file
f = open("[Link]", "r")
words = [Link]().split()
longest = max(words, key=len)
print("Longest word:", longest)
[Link]()
10. Reverse the content of the file
f = open("[Link]", "r")
data = [Link]()
[Link]()
f = open("[Link]", "w")
[Link](data[::-1])
[Link]()
11. Find and print lines starting with a specific word
f = open("[Link]", "r")
for line in f:
if [Link]("Hello"):
print([Link]())
[Link]()
12. Replace a word in the file
f = open("[Link]", "r")
data = [Link]().replace("text", "file")
[Link]()
f = open("[Link]", "w")
[Link](data)
[Link]()
13. Display only the first 3 lines of a file
f = open("[Link]", "r")
for i in range(3):
print([Link]().strip())
[Link]()
14. Display last 2 lines of a file
f = open("[Link]", "r")
lines = [Link]()
print(lines[-2:])
[Link]()
15. Write even length words to another file
f = open("[Link]", "r")
words = [Link]().split()
[Link]()
f2 = open("even_words.txt", "w")
for word in words:
if len(word) % 2 == 0:
[Link](word + "\n")
[Link]()
16. Copy contents from one file to another
f1 = open("[Link]", "r")
f2 = open("[Link]", "w")
[Link]([Link]())
[Link]()
[Link]()
17. Merge two files into a third
f1 = open("[Link]", "r")
f2 = open("[Link]", "r")
f3 = open("[Link]", "w")
[Link]([Link]())
[Link]("\n")
[Link]([Link]())
[Link]()
[Link]()
[Link]()
18. Remove all blank lines
f = open("[Link]", "r")
lines = [Link]()
[Link]()
f = open("[Link]", "w")
for line in lines:
if [Link]() != "":
[Link](line)
[Link]()
19. Count uppercase and lowercase letters in a file
f = open("[Link]", "r")
data = [Link]()
upper = sum(1 for ch in data if [Link]())
lower = sum(1 for ch in data if [Link]())
print("Uppercase:", upper)
print("Lowercase:", lower)
[Link]()
20. Write every word in new line
f = open("[Link]", "r")
words = [Link]().split()
[Link]()
f = open("[Link]", "w")
for word in words:
[Link](word + "\n")
[Link]()