Paul Zaino
Paul Zaino

Reputation: 100

Python For loop seems to be getting skipped over

This is my first question, so please be nice. I am leaning Python through an online course. I completed this assignment using Trinket, and it worked there. I submitted the code via the online grading system, and it passed there too. So, I already have been given 'credit' for this assignment.

When I try it in Idle or PyCharm, the code does not work. It seems to be skipping over the for loop completely.

I have looked at other answers on this type of question, but I cannot figure out how to apply them to my situation. Please help me understand why my for loop seems to be getting skipped.

fname = input("Enter file name: ")
fh = open(fname + ".txt")
x = fh.read()
count = 0
for line in fh:
    line = line.rstrip()
    word = line.split()
    if len(word) == 0:
        continue
    if word[0] != "From":
        continue
    else:
        print(word[1])
        count += 1
print("There were", count, "lines in the file with From as the first word")

In the .txt file being used, there are 27 email addresses that print out one by one, then the final line gives the total count. Like I said, it works in Trinket and the online code grader, but not in PyCharm or Idle.

Thanks in advance.

Upvotes: 1

Views: 124

Answers (2)

skjoshi
skjoshi

Reputation: 2533

When you do x = fh.read(), you are reading the content of file and storing it in variable x.

From Python documentation:

To read a file’s contents, call f.read(size), which reads some quantity of data and returns it as a string. size is an optional numeric argument. When size is omitted or negative, the entire contents of the file will be read and returned; it’s your problem if the file is twice as large as your machine’s memory. Otherwise, at most size bytes are read and returned. If the end of the file has been reached, f.read() will return an empty string ("").

So, once the file is read completely, fh is already at the end of file and iterating it with for loop is not yielding any new lines. You have two options here:

  1. Change for line in fh: with for line in x: OR
  2. Remove x = fh.read()

Upvotes: 1

bleand
bleand

Reputation: 376

You could try replacing

for line in fh:

with

for line in x:

or removing x = fh.read() since it'll read the entire file and left you with an empty file for the loop

Upvotes: 0

Related Questions