Reputation: 87
I am trying to read a row in a csv, which I have previously written.
That written row looks like this when is read: ['New York', '(30,40)']
and like this: ['New York', '(30,40)']
(converts the tuple in a string).
I need to read each item from the tuple to operate with the ints, but I can't if it is read like a string because if I do something like this: tuple[0]
, what I get is: '('
-the first character of the string tuple-
Maybe this is a question about how I write and read the rows, which actually is this way:
def writeCSV(data,name):
fileName = name+'.csv'
with open(fileName, 'a') as csvfile:
writer = csv.writer(csvfile, delimiter=',')
writer.writerow(data)
def readCSV(filename):
allRows = []
with open(filename, 'rb') as f:
reader = csv.reader(f, delimiter=' ')
for row in reader:
allRows.append(row)
return allRows
What I want is to read that tuple for row, not like a string, but like a tuple to operate with each item after. Is it possible?
Upvotes: 2
Views: 3378
Reputation: 140226
since you're producing the file yourself, why not making it right from the start:
import csv
data = ['New York', (30,40)]
with open("out.csv","w",newline="") as f:
cw=csv.writer(f)
cw.writerow(data) # wrong
cw.writerow(data[:1]+list(data[1])) # okay
the first line writes each item of data
but tries to convert each item as str
. tuple
gets converted, where selecting another format could avoid this.
New York,"(30, 40)"
which explains the need to evaluate it afterwards.
The second write line writes 3 elements (now 3 columns), but preserves the data (except for the int
part which is converted to str
anyway)
New York,30,40
in that case, a simple string to integer conversion on rows does the job.
Note that csv
isn't the best way to serialize mixed data. Better use json
for that.
Upvotes: 1
Reputation: 48090
You need to use ast.literal_eval()
on you tuple string as:
>>> my_file_line = ['New York', '(30,40)']
>>> import ast
>>> my_tuple = ast.literal_eval(my_file_line[1])
>>> my_tuple[0]
30
Because currently the list you got after reading the file at index 1 is holding the valid string of the tuple format. ast.literal_eval
will convert your tuple string to the tuple
object and then you can access the tuple based on the index.
Upvotes: 2