-
-
Save MichelleDalalJian/341754de0175074cffb59ab3490da032 to your computer and use it in GitHub Desktop.
fhand = open("mbox-short.txt") | |
count = 0 | |
for line in fhand: | |
line = line.rstrip() | |
if line == "": continue | |
words = line.split() | |
if words[0] !="From": continue | |
print(words[1]) | |
count = count+1 | |
print ("There were", count, "lines in the file with From as the first word") |
fname=input('enter a file name:')
file=open(fname)
c=0
for i in file:
if i.startswith('From '):
c=c+1
print(i.split()[1])
print('There were',c, 'lines in the file with From as the first word')
The Best Option
filee = open(input("Enter file name: "))
count = 0
for line in filee:
if not line.startswith("From"): continue
words = line.split()
if words[0] == "From:":conti
print(words[1])
count = count + 1
print("There were", count, "lines in the file with From as the first word"
I would like to ask what is the role of the command below?
if len(fname) < 1: fname = 'mbox-short.txt'
I think we do not need to specify, but I saw the code example and see that they have these two lines, which I am not sure how useful this is.
fname = input("Enter file name: ") if len(fname) < 1: fname = 'mbox-short.txt' fh = open(fname) count = 0 for line in fh: line = line.rstrip() if not line.startswith('From: ') : continue words = line.split() print(words[1]) count = count + 1 print("There were", count, "lines in the file with From as the first word")
if you are prompting the user to enter the file name, you don't need again to assign the file name. Compare my image below....
fname = input("Enter file name: ")
of = open(fname) #mbox-short.txt
count=0
for lines in of:
if lines.startswith('From '):
print("There were",count, "lines in the file with From as the first word")