Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Append Function Nested Inside IF Statement Body Not Working

I am fairly new to Python (just started learning in the last two weeks) and am trying to write a script to parse a csv file to extract some of the fields into a List:

from string import Template
import csv
import string

site1 = 'D1'
site2 = 'D2'
site3 = 'D5'
site4 = 'K0'
site5 = 'K1'
site6 = 'K2'
site7 = '0'
site8 = '0'
site9 = '0'
lbl = 1
portField = 'y'
sw = 5
swpt = 6
cd = 0
pt = 0
natList = []
with open(name=r'C:\Users\dtruman\Documents\PROJECTS\SCRIPTING - NATAERO DEPLOYER\NATAERO DEPLOYER V1\nataero_deploy.csv') as rcvr:
    for line in rcvr:
        fields = line.split(',')
        Site = fields[0]
        siteList = [site1,site2,site3,site4,site5,site6,site7,site8,site9]
        while Site in siteList == True:
            Label = fields[lbl]
            Switch = fields[sw]
            if portField == 'y':
                Switchport = fields[swpt]
                natList.append([Switch,Switchport,Label])
            else:
                Card = fields[cd]
                Port = fields[pt]
                natList.append([Switch,Card,Port,Label])
print natList

Even if I strip the ELSE statement away and break into my code right after the IF clause-- i can verify that "Switchport" (first statement in IF clause) is successfully being populated with a Str from my csv file, as well as "Switch" and "Label". However, "natList" is not being appended with the fields parsed from each line of my csv for some reason. Python returns no errors-- just does not append "natList" at all.

This is actually going to be a function (once I get the code itself to work), but for now, I am simply setting the function parameters as global variables for the sake of being able to run it in an iPython console without having to call the function.

The "lbl", "sw", "swpt", "cd", and "pt" refer to column#'s in my csv (the finished function will allow user to enter values for these variables).

I assume I am running into some issue with "natList" scope-- but I have tried moving the "natList = []" statement to various places in my code to no avail.

I can run the above in a console, and then run "append.natList([Switch,Switchport,Label])" separately and it works for some reason....?

Thanks for any assistance!

like image 968
riddleOFst33l Avatar asked Dec 28 '25 18:12

riddleOFst33l


1 Answers

It seems to be that the while condition needs an additional parenthesis. Just add some in this way while (Site in siteList) == True: or a much cleaner way suggested by Padraic while Site in siteList:.

It was comparing boolean object against string object.

like image 170
ssierral Avatar answered Dec 30 '25 07:12

ssierral