Python csv列表索引超出范围

2024-10-03 17:18:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试从json写入csv,所以每个值(pH)都在不同的行中,但我一直在获取

Traceback (most recent call last):
File "C:/Users/User/PycharmProjects/Meslosana/getValues.py", line 22, in
lines[i][1] = pH
IndexError: list index out of range

我还将在相同的行但不同的列中添加不同的值

我的csv文件看起来像这样,它没有空行

0,0,0,0,0
0,0,0,0,0
0,0,0,0,0
0,0,0,0,0
0,0,0,0,0
0,0,0,0,0
0,0,0,0,0
0,0,0,0,0
0,0,0,0,0

每次我运行代码时,它都会在底部创建一个空行

这是我的密码

import json
import csv

file = 'LaukiGeojson/Zemdegas.geojson'
cord = []
with open(file) as f:
    data = json.load(f)
i = 1
for feature in data['features']:
    cord = feature['geometry']['coordinates'][0]
    pH = feature['properties']['pH']
    print(pH)
    print(feature)
    print(data)
    # saglabaa
    r = csv.reader(open('LaukiAnalizes/Zemdegas.csv'))
    lines = list(r)

    print(len(lines))
    #lines[i][0] = 1
    lines[i][1] = pH
    #lines[i][2] = 1
    #lines[i][3] = 1
    #lines[i][4] = 1
    i += 1

    writer = csv.writer(open('LaukiAnalizes/Zemdegas.csv', 'w', newline=''))
    writer.writerows(lines)


# saglabaa
r = csv.reader(open('LaukiAnalizes/Zemdegas.csv'))
lines = list(r)
lines[0][0] = 'ID'
lines[0][1] = 'pH'
lines[0][2] = 'P'
lines[0][3] = 'K'
lines[0][4] = 'Mg'


writer = csv.writer(open('LaukiAnalizes/Zemdegas.csv', 'w', newline=''))
writer.writerows(lines)
open('LaukiAnalizes/Zemdegas.csv').close()

Tags: csvinimportjsondataopenphfeature
2条回答

Python是0索引的。这意味着第一行的索引为0,最后一个元素的索引为length-1。这就是您得到错误的地方,因为当i=9时,这将试图访问不存在的行。通过在开始时设置i=0而不是i=1来修复此问题

我将避免盲目假设CSV文件具有给定行数的代码。这样更好:

检查CSV中是否存在当前行,如果它更新了pH值,否则追加一个新行

import json
import csv

GEOJSON_FILE = 'LaukiGeojson/Zemdegas.geojson'
CSV_FILE = 'LaukiAnalizes/Zemdegas.csv'

with open(GEOJSON_FILE, encoding='utf8') as f:
    geo_data = json.load(f)

with open(CSV_FILE, encoding='utf8', newline='') as f:
    reader = csv.reader(f, delimiter=',')
    lines = list(reader)

for i, feature in enumerate(geo_data['features']):
    pH = feature['properties']['pH']
    if i < len(lines):
        lines[i][1] = pH
    else:
        lines.append([1, pH, 1, 1, 1])

with open(CSV_FILE, 'w', encoding='utf8', newline='') as f:
    writer = csv.writer(f, delimiter=',')
    writer.writerows(lines)

您打开和关闭CSV文件的次数对我来说似乎相当混乱。读一次,写一次。另外,对所有文件交互使用上下文管理器(with open(...) as ...)

相关问题 更多 >