简体   繁体   English

发行CSV模块python

[英]Issue CSV module python

I created a program to write a simple .csv (code below): 我创建了一个程序来编写一个简单的.csv(下面的代码):

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): .csv看起来像这样(中间是空行,但这不是问题):

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: 现在,我尝试读取.csv并将每个数字存储在变量中,但没有成功,请参见下面的数字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'] values现在为['36111', '96', '25887', '10128', '7', '398']

At the moment you're writing 6 rows into a csv file, with each row containing one column. 目前,您正在将6行写入一个csv文件,每行包含一列。 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 使用csv.writerows编写此csv.writerows将导致

36111, 96, 25887, 10128, 7, 398 36111、96、25887、10128、7、398

row[1] in your reading loop will return 96. 您的阅读循环中的row[1]将返回96。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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