user77005
user77005

Reputation: 1879

If clause dependent on file input doesn't seems to work

Can someone explain to me why in the following code the message "Found an instance without object" is not printed along with the output?

filename= "S1-ADL1.dat"

with open(filename, 'r')as data:
 for line in data:            
    valueList=line.split(' ')   
    print "valueList[247]"+valueList[247]
    print "valueList[249]"+valueList[249]        
    if valueList[247] == '0'  and valueList[249] == '0':
            print "Found an instance without object"
            continue
    elif valueList[247]==0 and valueList[249]!=0:
        valueList[247]=valueList[249]
        valueList[246]=valueList[248]                        
print filename+' is written'

The output I get is as follows

valueList[247]0
valueList[249]0

valueList[247]0
valueList[249]0

valueList[247]0
valueList[249]0

S1-ADL1.dat is written

As you can see there are instances where the if statement is satisfied but it does not print the message in the if clause.

Upvotes: 0

Views: 59

Answers (2)

Vivek Sable
Vivek Sable

Reputation: 10223

Agree with BartoszKP.

Use strip() method before split(' ') method.

Can can print valueList in your code and check List input by print "valueList:-" valueList ? So this will more clear to you.

I tested on some sample test case:

valueList:- ['q', '0', '0', '\n']
valueList[247]0
valueList[249]0
Found an instance without object
valueList:- ['q', '0', '0\n']
valueList[247]0
valueList[249]0

OR You can write if condition like following:

if valueList[247][0] == '0' and valueList[249][0] == '0':

Upvotes: 0

BartoszKP
BartoszKP

Reputation: 35911

This is because of the newline character hidden in the last result of the split. In each line you're reading you have something like this: 'x y ... z\n', so the last result of split contains 'z\n' (e.g. "0\n"). Alternatively it happens that it is the '\r' character, or some of other whitespace characters.

Try using strip:

valueList = line.strip().split(' ')

If it is possible that you have multiple other whitespace characters between pieces of you input you may try:

valueList = [v.strip() for v in line.split(' ')]

to remove them individually from each piece.

Also, your second condition is wrong. If you're not converting the pieces to int you should stay with strings:

elif valueList[247]=='0' and valueList[249]!='0':      # note the apostrophes

Upvotes: 2

Related Questions