Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (50.2k points)

I am executing the below code and it is printing an empty list. Why is that?

fname = input("Enter file name: ")

if len(fname) < 1 : fname = "mbox-short.txt"

fh = open(fname)

count = 0

lst = []

for line in fh:

    line = line.rstrip()

    word = line.split()

    if len(word) < 0:

        countinue

print(word[1])

1 Answer

0 votes
by (108k points)

There were two issues:

  • 1st is with the indentation, that is the reason for getting the empty print
  • 2nd is you I think unintentionally missed the space so that creates the duplicated or repeated result.

multiple repeated results

#Assignment 8.5

#file name = mbox-short.txt

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 '): #To check if the line staty with 'From '

            continue    #Note that there is a space behind the From, otherwise the print resuly would duplicated

    word = line.split()

    count = count + 1

    print(word[1]) #be careful with the indent

print("There were", count, "lines in the file with From as the first word")

 Want to get certified in Python? Register for this complete Python online course by Intellipaat.

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
asked Sep 11, 2019 in Python by Sammy (47.6k points)
0 votes
1 answer
asked Feb 9, 2021 in Python by ashely (50.2k points)

Browse Categories

...