Search code examples
pythoncsvdata-manipulationtxtcartesian-coordinates

Error Index out of Bound when trying to write data to new .txt file


I am trying to write a specific portion of data from a .txt file to a different .txt file for later use.

Code is below.

file = open(path, newline='')
reader = csv.reader(file)

header = next(reader)
data = [row for row in reader]

#read only cartesian points to new text file
f = open("Cartesian Points.txt", "w+")
#create a range from the first cartesian point 75054 to the last 1048576
for i in range(data[75054],data[1048576],1):
    f.write(data[i])
f.close()

My idea is to parse the original file completely, then create a range for the cartesian points and write this to a different .txt file for later use.

However when writing the data I am receiving an error

    for i in range(data[75054],data[1048576],1):
IndexError: list index out of range

I am confused as I know that the data ranges from cell 75054 to 1048576 and it should simply write that data to the new .txt file. I don't see why the data would continue on past the specified range.


Solution

  • The code for i in range(data[75054],data[1048576],1) actually takes the content of data at position 75054 as integer number for the range() function.

    From your question it seems you want to cycle inside the range 75054 <-> 1048576. This can be achived with for i in range(75054,1048576,1)

    With the code

    for i in range(75054,1048576):
        f.write(data[i])
    

    You cycle from 75054 to 1048576 and write into the file (object f) the content of data[i] at the position i (which is an integer inside the cycle)

    In the example above the 1 at the end in range() has been removed because it's set to 1 as default by Python itself

    Some documentation about range(). You may also want to check lists in Python