0% found this document useful (0 votes)
12 views8 pages

Python Text File Handling Examples

The document provides a comprehensive guide on various Python programs for handling text files, including writing, reading, counting lines and words, and manipulating text. It covers functions for specific tasks such as counting occurrences of words, replacing characters, and displaying content based on conditions. Each program is presented with code snippets and explanations for clarity.

Uploaded by

mryoshi3020
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views8 pages

Python Text File Handling Examples

The document provides a comprehensive guide on various Python programs for handling text files, including writing, reading, counting lines and words, and manipulating text. It covers functions for specific tasks such as counting occurrences of words, replacing characters, and displaying content based on conditions. Each program is presented with code snippets and explanations for clarity.

Uploaded by

mryoshi3020
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

TEXT FILE PROGRAMS

1. Write and Read a Text File


f = open("[Link]", "w")
[Link]("Python File Handling is simple!\n")
[Link]("This is line two.")
[Link]()

f = open("[Link]", "r")
print([Link]())
[Link]()

2. Write and Read Contents of a Text File Using writelines()

f = open("[Link]", "w")

lines = [
"Python is a powerful programming language.\n",
"It is easy to learn and use.\n",
"File handling is an important concept in Python.\n"
]

[Link](lines)
[Link]()
print("Data written successfully")

# --- Reading from file ---


f = open("[Link]", "r")
content = [Link]()
print("\nContents of the file:\n")
print(content)
[Link]()
3. Count Number of Lines in a File (using readline())

f = open("[Link]", "r")
count = 0
line = [Link]()
while line != "":
count += 1
line = [Link]()
print("Total Lines:", count)
[Link]()
4. Count Number of Words in a File

f = open("[Link]", "r")
text = [Link]()
words = [Link]()
print("Total Words:", len(words))
[Link]()

or

f = open("[Link]", "r")
text = [Link]()
words = [Link]()
c=0
for i in words:
c=c+1
print("Total Words:", c)
[Link]()

5. Print Alternate Lines from a File

f = open("[Link]", "r")
line_no = 1
line = [Link]()
while line != "":
if line_no % 2 != 0:
print([Link]())
line = [Link]()
line_no += 1
[Link]()

6. Count How Many Times the Word "he" or "she" Appears


f = open("[Link]", "r")
data = [Link]().lower().split()
he_count = [Link]("he")
she_count = [Link]("she")
print("Word 'he' occurs:", he_count, "times")
print("Word 'she' occurs:", she_count, "times")
[Link]()
or

f = open("[Link]", "r")
data = [Link]().lower()
w=[Link]()
c=0
c1=0
for i in w:
if i=="he":
c+=1
if i=="she":
c1+=1

print("Word 'he' occurs:", c, "times")


print("Word 'she' occurs:", c1, "times")
[Link]()

or

f = open("[Link]", "r")
data = [Link]().lower()
w=[Link]()
c=0
for i in w:
if i=="he" or i=="she":
c+=1
print("Word he or she occurs:", c, "times")
[Link]()

7. Count Uppercase, Lowercase, Digits, and Spaces


f = open("[Link]", "r")
text = [Link]()
u=l=d=s=0
for ch in text:
if [Link]():
u += 1
elif [Link]():
l += 1
elif [Link]():
d += 1
elif [Link]():
s += 1
print("Uppercase:", u, "Lowercase:", l, "Digits:", d, "Spaces:", s)
[Link]()
8. Count How Many Lines Contain the Word “India”.

f = open("[Link]", "r")
count = 0
line = [Link]()
while line != "":
if "india" in [Link]():
count += 1
line = [Link]()
print("Lines containing 'India':", count)
[Link]()

9. Copy Alternate Lines into Another File

f1 = open("[Link]", "r")
f2 = open("[Link]", "w")
line_no = 1
line = [Link]()
while line != "":
if line_no % 2 != 0:
[Link](line)
line = [Link]()
line_no += 1
[Link]()
[Link]()
print("Alternate lines copied to '[Link]'.")

[Link] Vowels and Consonants

f = open("[Link]", "r")
text = [Link]().lower()
vowels = "aeiou"
v=c=0
for ch in text:
if [Link]():
if ch in vowels:
v += 1
else:
c += 1
print("Vowels:", v, "Consonants:", c)
[Link]()
[Link] All Spaces with ‘#’ and Rewrite to the Same File

f = open("[Link]", "r")
data = [Link]()

# Step 2: Replace all spaces with '#'


data = [Link](" ", "#")
[Link]()
# Step 3: Open the same file in write mode and write modified content
f = open("[Link]", "w")
[Link](data)
[Link]()

print("All spaces have been replaced with '#' and file updated successfully.")
f=open("[Link]","r")
print([Link]())
[Link]()

[Link] a method in python to read lines from a text file “[Link]” and
display those lines which starts with the alphabet “p”.

def display():
f=open("[Link]","r")
l=[Link]()
while l:
if l[0]=="p":
print(l)
l=[Link]()
[Link]()
display()

or

def display():
f=open("[Link]","r")
l=[Link]()
for i in l:
if i[0]=="p":
print(i)
[Link]()
display()
[Link] a function countmy() in python to read the textfile “[Link]” and
count the number of times “my” occurs in the file.
def countmy():
f=open("[Link]","r")
c=0
l=[Link]()
w=[Link]()
for i in w:
if i=="my":
c=c+1
print("my occurs",c,"times")
countmy()
[Link] the longest line from the file

def fun(filename):
f=open(filename,"r")
longest=""
l=[Link]()
while l:
if len(l)>len(longest):
longest=l
l=[Link]()
print("longest line=",longest)
fun("[Link]")

[Link] a text file and display all words that starts with "t" or "a".
f = open("[Link]", "r")
# Read all contents
l = [Link]()
# Split into words
w = [Link]()
print("Words starting with 't' or 'a':")
# Check each word
for i in w:
if [Link]().startswith('t') or [Link]().startswith('a'):
print(i)
[Link]()

OR

f = open("[Link]", "r")
l=[Link]()
for i in l:
w=[Link]()
for j in w:
if j[0]=="a" or j[0]=="t":
print(j)
[Link]()

[Link] how many words have more than 4 characters in a text file.
def count_long_words():
with open("[Link]", "r") as f:
data = [Link]() # read full text
words = [Link]() # split into words

count = 0
for word in words:
if len(word) > 4:
count += 1

print("Number of words with more than 4 characters:", count)

count_long_words()
[Link] how many lines in a text file have more than 20 characters.
with open("[Link]", "r") as f:
count = 0
l=[Link]()
for i in l:
i = [Link]() # remove extra spaces and newline
if len(i) > 20: # check line length
count += 1

print("Number of lines with more than 20 characters:", count)

[Link] all words from a text file that contain @[Link].


def display_gmail_words():
with open("[Link]", "r") as f:
data = [Link]() # read the entire file
words = [Link]() # split into individual words

print("Words containing '@[Link]':")


for word in words:
if "@[Link]" in word:
print(word)
display_gmail_words()
[Link] a text file and display every sentence on a separate line.
def display_sentences():
with open("[Link]", "r") as f:
data = [Link]() # Read the entire file

# Replace sentence-ending punctuation with newline


data = [Link]('.', '.\n')
data = [Link]('?', '?\n')
data = [Link]('!', '!\n')

print("Sentences in separate lines:\n")


print(data)

display_sentences()

OR

def display_sentences():
with open("[Link]", "r") as f:
l = [Link]() # Read the entire file
sentence = "" # Temporary variable to store characters

for i in l:
sentence += i
if i in [".", "?", "!"]: # check for sentence end
print([Link]()) # print the complete sentence
sentence = "" # reset for next sentence

display_sentences()

[Link] all occurrences of "is" with "are" in a text file.


def replaceword():
f = open("[Link]", "r") # open file for reading
data = [Link]()
[Link]()

# replace all 'is' with 'are'


new_data = [Link]("is", "are")

f = open("[Link]", "w") # open file for writing


[Link](new_data)
[Link]()

print("All 'is' have been replaced with 'are'.")


replaceword()

****************

You might also like