Reputation: 49
I'm trying to write from json to csv, so each value(pH) is in different row, but I keep getting
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
I will also add different values in the same rows but different columns.
My csv file looks like this, it does not have empty lines.
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
and each time I run my code it creates empty line at the bottom.
Here is my code
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()
Upvotes: 1
Views: 307
Reputation: 338248
I would avoid code that blindly assumes that a CSV file has a given number of lines. This is better:
Check if the current line even exists in the CSV, if it does update the pH
value in-place, otherwise append a new line.
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)
The number of times you are opening and closing the CSV file seemed rather confusing to me. Read it once, write it once. Also, use a context manager (with open(...) as ...)
for all your file interactions.
Upvotes: 1
Reputation: 99
Python is 0-indexed. This means the index of the first line is 0, and the index of the final element is length-1. This is where you get the error, as when your i=9, this will be attempting to access a row that doesn't exist. Fix this by setting i=0
at the start instead of i=1
.
Upvotes: 0