2013-07-12 120 views
0

我試圖從csv中獲取數據並將其插入到mysql表中。試圖獲取Syntax Error。請幫我解決這個錯誤。SyntaxError:解析時意外的EOF

代碼

 
import csv 
import MySQLdb as mdb 
import ast 
cr = csv.reader(open("tushar.csv","rb")) 
k=0 
con = mdb.connect('***', '***', '***', '****') 
cur = con.cursor() 
for row in cr: 
    if k%2==0: 
     t=row 
     print t 
    else: 
     l1=row 
     l=ast.literal_eval(l1[0]) 
     sql="INSERT INTO amazon_order (orderno,mainStatus,stateCode,timeStamp,destZip,orderDate,cost) Values('%s','%s','%s')"%(t,l["status"],l["state_code"],l["processed_timestamp"],l["destination_zip"],l["odr_date"],l["cost"]) 
     print sql 
     cur.execute(sql) 
     con.commit() 
    k+=1 
if con: 
    con.close()  

錯誤

 
['497832'] 
Traceback (most recent call last): 
    File "linkedlist.py", line 14, in 
    l=ast.literal_eval(l1[0]) 
    File "/usr/lib/python2.7/ast.py", line 49, in literal_eval 
    node_or_string = parse(node_or_string, mode='eval') 
    File "/usr/lib/python2.7/ast.py", line 37, in parse 
    return compile(source, filename, mode, PyCF_ONLY_AST) 
    File "", line 1 
    {"status": "All items processed" 
           ^
SyntaxError: unexpected EOF while parsing 

tushar.csv

 
497832 
{"status": "All items processed", "state_code": "GA", "processed_timestamp": "2013/05/14 19:32:08 UTC", "destination_zip": "31028", "odr_date": "2013-05-13 00:00:00""cost": 54.08} 
487870 
{"status": "All items processed", "state_code": "CT", "processed_timestamp": "2013/03/11 22:15:43 UTC", "destination_zip": "06468", "odr_date": "2013-03-11 00:00:00","cost": 149.43} 
and so on.. 
+1

您的數據被截斷,它出現。 –

回答

0

你不應該使用CSV。您的文件不是以逗號分隔的值格式。 CSV將文件行分割爲不可分片。

採取

{"status": "All items processed", "state_code": "GA", "processed_timestamp": "2013/05/14 19:32:08 UTC", "destination_zip": "31028", "odr_date": "2013-05-13 00:00:00""cost": 54.08} 

,並把它分解的 '' 你會得到一個列表:

['{"status": "All items processed"', 
'"state_code": "GA"', 
'"processed_timestamp": "2013/05/14 19:32:08 UTC"', 
(etc..) 

也就是說第一行看有點熟悉。

只要打開文件並逐行閱讀 - 完全跳過csv的東西。

相關問題