1

While reading the csv using python csv library, it adds single quote to all the values.

Here is the code which reads the csv -

with open(csvfile, 'rb') as data:
    reader = csv.reader(data)
    for row in reader:
        print row

CSV file content -

1,XYZ (A),ABC,7.05,13.10

while reading in python with csv.reader reads row in below format -

['1', 'XYZ (A)', 'ABC', '7.05', '13.10']

expected output -

[1, 'XYZ (A)', 'ABC', 7.05, 13.10]

I tried using quoting format, but no luck.

The other option I was thinking to convert it to appropriate format by individually iterating over the items in row read by csv.reader(file)

Any suggestion?

2
  • Looking at the data will you always know the first column is and integer and the last two a float? Commented Apr 4, 2014 at 22:13
  • No. The logic has to be generic enough to support later integer as well. Commented Apr 4, 2014 at 22:43

1 Answer 1

3

You can do it like this:

with open(csvfile, 'rb') as data:
    reader = csv.reader(data)
    for row in reader:
        print row
        temp = []
        for r in row:
            try:
                temp.append(float(r))
            except ValueError:
                temp.append(r)

        print temp

Giving the following output:

['1', 'XYZ (A)', 'ABC', '7.05', '13.10']
[1.0, 'XYZ (A)', 'ABC', 7.05, 13.1]

With temp being the correct format

Edit

To get around the int being cast to a float:

with open(csvfile, 'rb') as data:
    reader = csv.reader(data)
    for row in reader:
        print row
        temp = []
        for r in row:
            try:
                if "." in row:
                    temp.append(float(r))
                else:
                    temp.append(int(r))
            except ValueError:
                temp.append(r)

        print temp

Giving the new output:

['1', 'XYZ (A)', 'ABC', '7.05', '13.10']
[1, 'XYZ (A)', 'ABC', '7.05', '13.10']
Sign up to request clarification or add additional context in comments.

2 Comments

First column is integer, with this approach it will add the decimal points. Also, do you think there will be performance hit with try except approach?
There will be a slight performance hit, yeah. To get around the float appose to an int you could check the string value before casting it to see if it contains a period or not and cast it appropriately.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.