简体   繁体   中英

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!

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.

Change

while Site in siteList == True:

to

if Site in siteList:

You might want to look into the csv module as this module attempts to make reading and writing csv files simpler, eg:

import csv

with open('<file>') as fp:
    ...
    reader = csv.reader(fp)
    if portfield == 'y':
        natlist = [[row[i] for i in [sw, swpt, lbl]] for row in fp if row[0] in sitelist]
    else:
        natlist = [[row[i] for i in [sw, cd, pt, lbl]] for row in fp if row[0] in sitelist]

print natlist

Or alternatively using a csv.DictReader which takes the first row as the fieldnames and then returns dictionaries:

import csv

with open('<file>') as fp:
    ...
    reader = csv.DictReader(fp)
    if portfield == 'y':
        fields = ['Switch', 'card/port', 'Label']
    else:
        fields = ['Switch', '??', '??', 'Label']
    natlist = [[row[f] for f in fields] for row in fp if row['Building/Site'] in sitelist]

print natlist

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM