Nasos Gkimi Nasos Gkimi - 3 months ago 6
Python Question

I want to transfer data from text file to array

i'm new here and also new with programming with python
as an exercise i have to read data (lat & lon) from a txt file with many rows and convert them into shapefile with QGIS

After reading i find a way to extract data into array, as step1, but i have soem issues..

I use the following code

f = open('D:/test_data/test.txt','r')
for line in f:
triplets=f.readline().split() #error
for i in X:
print X[i]

with error:

ValueError: Mixing iteration and read methods would lose data

Propably it's a warning for losing the rest rows but i really don't want them for now.


for line in f: already iterates through the lines in the file, reading as it goes along. As such, it should be:

for line in f:
    triplets = line.split()

Alternatively, you could do as below, though I recommend the method above.

with open('D:/test_data/test.txt','r') as f:
    content = f.readlines()
    for line in content:
        triplets = line.split()
        # append()

See Reading and Writing Files in python for more info.

Also, append() does what it sounds like, so you don't need assignment.

X.append(triplets[0])  # not X=X.append(triplets[0)