简体   繁体   中英

Issue CSV module python

I created a program to write a simple .csv (code below):

opencsv = open('agentstatus.csv', 'w')
a = csv.writer(opencsv)
data = [[agents125N],
    [okstatusN],
    [warningstatusN],
    [criticalstatusN],
    [agentdisabledN],
    [agentslegacyN]]
a.writerows(data)
opencsv.close()

The .csv looks like this (it's with empty rows in the middle, but it's not a problem):

36111

96

25887

10128

7

398

Now I am trying to read the .csv and store each of this numbers in a variable, but without success, see below an example for the number 36111:

import csv 

with open('agentstatus.csv', 'r') as csvfile:
    f = csv.reader(csvfile)
    for row in f:
        firstvalue = row[0]

However, I get the error:

line 6, in <module>
    firstvalue = row[0]
IndexError: list index out of range

Could you support me here?

Your file contains empty lines, so you need to check the length of the row:

values = []
for row in f: 
    if len(row) > 0:
        values.append(row[0])

values is now ['36111', '96', '25887', '10128', '7', '398']

At the moment you're writing 6 rows into a csv file, with each row containing one column. To make a single row with six columns, you need to use a list of values, not each value in its own list.

ie change

data = [[agents125N], [okstatusN], [warningstatusN], [criticalstatusN], [agentdisabledN], [agentslegacyN]]

to

data = [[agents125N, okstatusN, warningstatusN, criticalstatusN, agentdisabledN, agentslegacyN]]

(a list containing one list of six values). Writing this with csv.writerows will result in

36111, 96, 25887, 10128, 7, 398

row[1] in your reading loop will return 96.

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