-1

I want to extract data from a file and change the value of an entry with a 'for-loop'.

f = open(r"C:\Users\Measurement\LOGGNSS.txt", "r")
x=0
content = [[],[]]
for line in f:
    actualline = line.strip()
    content.append(actualline.split(","))
    x+=1
f.close

print(x)
for z in range(x):
    print(z)
    print(content[z][1])

IndexError: list index out of range

Using a real value instead of the variable 'z' works fine. But I need to change all first entries in the whole 2D-Array. Why it does not work?

Teymour
  • 1,832
  • 1
  • 13
  • 34
Mat
  • 63
  • 8

2 Answers2

0

You initialize your content with two empty arrays, so both of these will fail to find the first index ([1]), just initialize it with an empty array

content = []
Sayse
  • 42,633
  • 14
  • 77
  • 146
0

Your code has several problems. First of all, use the with statement to open/close files correctly. Then, you don't need to use a variable like x to keep track of the number of lines, just use enumerate() instead!

Here is how I would refactor your code to make it slimmer and more readable.

input_file = r"C:\Users\Measurement\LOGGNSS.txt"
content = []

with open(input_file, 'r') as f:
    for line in f:
        clean_line = line.strip().split(",")
        content.append(clean_line)

for z, data in enumerate(content):
    print(z,'\n',data)

Note that you could print the content while reading the file in one single loop.

with open(input_file, 'r') as f:
    for z, line in enumerate(f):
        clean_line = line.strip().split(",")
        content.append(clean_line)
        print(z,'\n', clean_line)

Finally, if you are dealing with a plain and simple csv file, then use the csv module from the standard library.

import csv

with open(input_file, 'r') as f:
    content = csv.reader(f, delimiter=',')
alec_djinn
  • 10,104
  • 8
  • 46
  • 71