1

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()
5
  • 1
    could you add the full traceback for the error? Commented Jun 29, 2020 at 11:24
  • What makes you so sure that lines[i] even exists? Commented Jun 29, 2020 at 11:26
  • variable i should be from 1-9 and my csv file has 9 lines Commented Jun 29, 2020 at 11:28
  • 2
    you start with an i of 1 .... and increment it once per line .... in python we count from 0 to len()-1 - so if you got 9 lines you have a list from index 0 to 8. not 9. Commented Jun 29, 2020 at 11:30
  • but i get error even if i is 1 or 2 Commented Jun 29, 2020 at 11:32

2 Answers 2

0

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

1 Comment

I still get the error, I tried printing out i and it stopped at 2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.