Sabeer Ph
Sabeer Ph

Reputation: 1

nested loop code not working please

with open(sys.argv[2]) as f:
     processlist = f.readlines()
     for a in range(0,1):
         process = processlist[a]
         print process
         for b in range(0,3):
             process1 = process.split()
             print process1[b]

sys.argy[2 ] files just has 2 sentences

Sunday Monday
local owner public

I am trying to read once sentence at a time and in each sentence I am trying to access one word at a time.... I am able to get the things i need individually but the loop doesn’t not iterate... it stops after first iteration....

Upvotes: 0

Views: 76

Answers (2)

Tim Pietzcker
Tim Pietzcker

Reputation: 336148

To answer your question why the loop doesn't iterate:

range(0,1)

contains only the element 0, since the upper bound is not included in the result. Similarly,

range(0,5)

would, when viewed as a list, be [0,1,2,3,4].

The correct way to iterate over a file is demonstrated by @HennyH's answer.

Upvotes: 2

HennyH
HennyH

Reputation: 7944

with open(sys.argv[2]) as f:
    for line in f: #iterate over each line
        #print("-"*10) just for demo
        for word in line.rstrip().split(): #remove \n then split by space
            print(word)

Over your file would produce

----------
Sunday
Monday
----------
local
owner
public

Upvotes: 3

Related Questions