Reputation: 110592
I have exported a file as a CSV. In excel, the data is all in the first column (four columns per row), and it looks like this --
like "name" "email" "message"
"yes" "John Smith" "[email protected]" "My message"
...etc.
When I import the file, this is what I get --
'"""like"",""name"",""email"",""message"""\r""
"yes"",""John Smith"",""[email protected]"",""My message"""'
How would I convert this string in Python so that I can insert the it into a database? I imagine that I'd need to separate each row into a list, and run a for loop to zip the first row with all the others. Then create a dict from the list of tuples and insert that into the db. Does this method seem correct? How would I convert this odd string into that -- I was having difficulty trying to do so? Thank you.
Update
Granted this is not the most efficient/practical method to do this...
Going in reverse from the end --
{'like':'yes','name':'John Smith','email': '[email protected], 'message': 'My message'}
This could be arrived at by doing --
zip[('like','name','email','message'),('yes','name','email','message')]
And using a for loop so the zip would be performed on (tuple[0],tuple[n])
.
So, how would I convert the raw python string into a list of tuples such that I could add it to the database -- is is there a better way to do this (excluding the use of python modules to accomplish this easily)?
Upvotes: 0
Views: 3053
Reputation: 2427
Use Python's standard library to parse the CSV file and extract the data you need to put into your database:
import csv
with open('some.csv', 'rb') as f:
reader = csv.reader(f, delimiter=' ')
for row in reader:
print row
Source: http://docs.python.org/library/csv.html
Upvotes: 2