开发者

Python script to convert csv to dump into database

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"  "John@gmail.com"  "My message"
 ...etc.

When I import the file, this is what I get --

'"""like"",""name"",""email"",""message"""\r""
"yes"",""John Smith"",""John@gmail.com"",""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': 'John@gmail.com, '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)?


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜