[英]Python csv list index out of range
我正在嘗試從 json 寫入 csv,所以每個值(pH)都在不同的行中,但我不斷得到
回溯(最近一次通話最后):
文件“C:/Users/User/PycharmProjects/Meslosana/getValues.py”,第 22 行,在
線[i][1] = pH
IndexError:列表索引超出范圍
我還將在相同的行但不同的列中添加不同的值。
我的 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()
我會避免盲目假設 CSV 文件具有給定行數的代碼。 這個更好:
檢查當前行是否甚至存在於 CSV 中,如果它確實就地更新了pH
值,否則 append 一個新行。
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...)
。
Python 為 0 索引。 這意味着第一行的索引為 0,最后一個元素的索引為 length-1。 這是你得到錯誤的地方,當你的 i=9 時,這將試圖訪問一個不存在的行。 通過在開始時設置i=0
而不是i=1
來解決此問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.