问题
I'm having a little problem using csv.reader.
I have two files:
FileA corresponds to 9 geographical coordinates (x (column1) and y(column2), with no headers). The file is save from excel into a csv file.
301506 5918202
301012 5919417
309769 5919926
299337 5924043
299602 5924730
305310 5907794
300634 5927108
303968 5922319
303684 5922062
304882 5922009
FileB which is a random sequence of 9 integers between 0 and 8. The file is save as an csv file from excel. The data are in row 1.
6 3 7 8 5 1 2 4 0
here is the code:
import csv
FileA = csv.reader(open(‘FileA.csv’,'rb'),delimeter=',')
coord_list = []
coord_list.extend(FileA)
coordinates = []
for data in coord_list:
coordinates.append(data[0])
print coordinates
FileB = csv.reader(open(‘FileB.csv’,'rb'),delimeter=',')
seq_list = []
seq_list.extend(FileB)
sequence = []
for data in seq_list:
sequence.append(data[0])
print sequence
FileC = []
for i range(0,8,1):
FileC[sequence[i], 1] = coordinates[i,1]
FileC[sequence[i], 2] = coordinates[i,2]
print FileC
but i get :
File "C:\generatesequence\script.py", line 19, in <module>
FileC[sequence[i], 1] = coordinates[i,1]
TypeError: list indices must be integers, not tuple
I want to build the FileC to be able to use it after in ArcMAP
Any advice is welcome :)
回答1:
a[b, c]
indexes a
with the tuple (b, c)
. You need to think hard about what you really want to do at the specific lines where you do this.
回答2:
You are try to access list with the tuple. Please try file[sequence[i]: 1] = coordinates[i:1]
.
回答3:
For example
test.csv:
'a,b,c,d,f,g'
In [2]: import csv
In [3]: spamReader = csv.reader(open('test.csv', 'rb'), delimiter=',', quotechar='|')
In [4]: spamReader
Out[4]: <_csv.reader object at 0x1e34ec0>
In [5]: spamReader.next()
Out[5]: ['a', 'b', 'c', 'd', 'f', 'g']
the csv.reader returns an object is an iterator, not a tuple or list. Hence FileA should be an iterator (you can't directly convert it to list)
回答4:
You are accessing lists incorrectly: you cannot access two-dimensional lists using a comma, as you would in R or MATLAB. Please look over Python lists very thoroughly.
Based on your code, I think this should accomplish what you are trying to do:
import csv
FileA = csv.reader(open(‘C:/testing/FileA.csv’,'rb'),delimeter',')
FileB = csv.reader(open(‘C:/testing/FileB.csv’,'rb'),delimeter',')
FileC = [0] * 10
for lineA, lineB in zip(FileA, FileB):
FileC[int(lineB[0])] = lineA
print FileC
来源:https://stackoverflow.com/questions/9372910/from-tuple-to-integer-using-csv-files