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'"]
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)
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.