I am learning File Handling in python. I tried to write a program to display the number of lines starting with 'H' and the total number of words in the file. Even though the text file is not empty, it only printed 0 for both. What's wrong here?
with open("para.txt","a+") as f:
f.write("As I said: not all things should be left up to god.")
lines = 0
# to display the number of lines starting with H
l = f.readlines()
for i in l:
if i[0] == "H":
lines += 1
print("No. of lines starting with H is", lines)
#to display the total number of words in the file
data = f.read()
split_data = data.split()
count = 0
for i in split_data:
count += 1
print("Total number of words:", count)
print(f.tell())
try:
def f(file_path):
with open(file_path) as f:
lines = [line.strip() for line in f.readlines() if line.strip()]
length_of_lines = len(lines)
length_of_lines_start_with_h = len([i for i in lines if i[0] == 'H'])
return [length_of_lines, length_of_lines_start_with_h]
f('b.txt') #supposing a text file in you computer named "b.txt"
# [8, 1] #--> 8 lines, 1 line start with 'H'
with open("para.txt","r") as f:
text=f.readline()
l_text=text.split(".")
lines=0
words=0
word_list=[]
for i in l_text:
splited=i.split(" ")
word_list.append(splited)
if i[0].lower() =="h":
lines+=1
for i in word_list:
if i[0].lower() == "h":
word+=1
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.