4

I have a CSV with following values

ID, Value
1, a
2, b
3, c

How can I convert this csv to following string using Python

[('ID', 'Value'), (1, 'a'), (2, 'b'), (3, 'c')]

I was trying with the following code

with open('sample.csv', 'rb') as csvfile: 
    reader = csv.reader(csvfile, delimiter=' ', quotechar='|')
    for row in reader:
        data = ', '.join(row)
        rows.append(data)
print rows

Am getting following output only

["'ID','Value'", "1,'a'", "2,'b'", "3,'c'"]
3
  • 2
    [('ID', 'Value'), (1, 'a'), (2, 'b'), (3, 'c')] isn't a string. It's a list of tuples. The first tuple contains 2 strings, the other tuples contain an int and a string. So do you want that list, or do you really want a string representation of that list? Commented Dec 6, 2017 at 10:25
  • I just want to read the csv that contains two columns like in the question and then need to convert to above mentioned format(even its a string or list or tuples). Am not good in Python. So saying the above representation as string Commented Dec 6, 2017 at 10:28
  • Yes, thats working Commented Dec 6, 2017 at 10:38

2 Answers 2

1

To produce the list [('ID', 'Value'), (1, 'a'), (2, 'b'), (3, 'c')] from that CSV data you need to convert the number strings to integer. Here's one way to do that in Python 2.

import csv

data = []
with open('sample.csv', 'rb') as csvfile: 
    reader = csv.reader(csvfile, skipinitialspace=True)
    data.append(tuple(next(reader)))
    for num, val in reader:
        data.append((int(num), val))

print data

output

[('ID', 'Value'), (1, 'a'), (2, 'b'), (3, 'c')]

The csv.reader yields each row of the CSV data as a list. We need to extract the items from that list and convert the 1st one to an int. And then we can pack the two items into a tuple and append it to the data list. However, the header line contains two strings, so we don't want to perform that conversion on the header line.

This code:

data.append(tuple(next(reader)))

gets the header line and just converts it to a tuple and appends the result to our data list.


Note that the Python 2 csv module requires you to open the file in 'rb' mode, but in Python 3 you need to open the file in 'r' mode. Please see the respective module docs for further details. Apart from that, and using the print function instead of the print statement, no other changes are needed to run the above code on Python 3.

Sign up to request clarification or add additional context in comments.

4 Comments

If the csv is having more columns then is there any general method to this?
@PraveenVT Sure, but the best way to do it depends on the types of data in the other columns, eg if there are numbers that need to be converted to int or float. OTOH, if you just want to read the CSV data and write it back out as a different file format then there's not need to perform that conversion. I suggest you add a short example of your input data with more columns to your new question, and clearly show the desired output format.
Ok, let me create one sample, but then similar to real data
added a short example in my new question stackoverflow.com/questions/47672157/…
1

Do not read with rb but just r:

with open('sample.csv', 'r') as csvfile:
    csvtext = csvfile.readlines()

mylist = []
for line in csvtext:
    mylist.append(tuple(line.strip().split(', ')))
print(mylist)

6 Comments

OP has no issue with it because he probably runs python 2 (in python 3 it crashes immediately). But you're right (that doesn't answer the question though)
But am getting this out put [('ID,Value',), ('1,a',), ('2,b',), ('3,c',)] Instead i need, [('ID', 'Value'), (1, 'a'), (2, 'b'), (3, 'c')]
That means, I need single quotes for character and no quotes for numeric. Or even singles quotes for all value also fine
No. From my solution you are getting: [('ID', 'Value'), ('1', 'a'), ('2', 'b'), ('3', 'c')] which has single quotes for all values as you just requested...
@mrCarnivore No, am getting like this only [('ID,Value',), ('1,a',), ('2,b',), ('3,c',)]
|

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.