npm
npm

Reputation: 653

How can I create tuple from CSV file without quotes?

I'm reading CSV file and need to make tuples but I need to get rid the quotations. CSV lines examples:

57, 47, 1.04
1288, 317, 1.106
149, 84, 1.05

I tried this

import csv
from pprint import pprint

with open('./Documents/1.csv', encoding='utf-8-sig') as file:
   reader = csv.reader(file, skipinitialspace=True)
   x = list(map(tuple, reader))

and the results are:

[('57', '47', '1.04'),
 ('1288', '317', '1.106'),
 ('149', '84', '1.05')]

and I need it to be

[(57, 47, 1.04183),
 (1288, 317, 1.106),
 (149, 84, 1.05)]

Found similar question here but can't figure out the answer yet.

Upvotes: 1

Views: 2223

Answers (3)

backtrack
backtrack

Reputation: 8144

def num(s):
        try:
            return int(s)
        except ValueError:
            return float(s)


with open('1.csv', encoding='utf-8-sig') as file:
   reader = csv.reader(file, skipinitialspace=True)
   output = [tuple(map(num, x)) for x in map(tuple, reader)]
   print(output)

output:

[(57, 47, 1.04), (1288, 317, 1.106), (149, 84, 1.05)]

Upvotes: 0

RoadRunner
RoadRunner

Reputation: 26315

You can use ast.literal_eval() to convert the numbers inside the tuples to their respective types:

import csv
from ast import literal_eval
from pprint import pprint

with open('1.csv', encoding='utf-8-sig') as file:
   reader = csv.reader(file, skipinitialspace=True)
   x = [tuple(map(literal_eval, x)) for x in map(tuple, reader)]
   print(x)
   # [(57, 47, 1.04), (1288, 317, 1.106), (149, 84, 1.05)]

Upvotes: 2

F.Igor
F.Igor

Reputation: 4350

This needs to add an extra processing, converting with type casting:

reader = csv.reader(file, skipinitialspace=True)
# if the file has a header
# header = next(reader)
rows = [[float(row[0]), float(row[1]), float(row[2])] for row in reader]
print rows

Upvotes: 1

Related Questions