2009-12-02 85 views
0

我从source.sql读(sql脚本)文件python编码问题?

INSERT INTO `Tbl_abc` VALUES (1111, 2222, 'CLEMENT', 'taya', 'MME', 'Gérant', NULL, NULL, NULL, NULL, NULL, NULL, NULL, 4688, 0, NULL, NULL, 'MAILLOT 01/02/09', 'MAILLOT 01/04/09', NULL, NULL); 

和写入dest.sql随着我的列表格式化

我与编码遇到的问题,例如:

Gérant= G\xc3\xa9rant 

我在想什么

def DataMigration(dest, source, tbl_name, return_data=True): 
    '''  
    ''' 
    data = [] 
    for ln in codecs.open(source, 'r', "utf-8").xreadlines(): 
     replace1 = ln.replace("INSERT INTO `"+tbl_name+"` VALUES (", "") 
     replace2 = replace1.replace(");", "") 
     list_replace = replace2.split(',')   
     s = list_replace 
     data.append(list_replace) 

    if return_data == True: 
     ouputdata = [d for d in data if d[1] == ' 0' and d[6]==' 0'] 
     return ouputdata 
    if return_data == False: 
     return data 

我打印 打印DataMigration( 'dest.sql', '.source.sql', 'Tbl_abc',FALSE)

输出

[['1111', ' 2222', " 'CLEMENT'", " 'taya'", " 'MME'", " 'G\xc3\xa9rant'", ' NULL', ' NULL', ' NULL', ' NULL', ' NULL', ' NULL', ' NULL', ' 4688', ' 0', ' NULL', ' NULL', " 'MAILLOT 01/04/09'", " 'MAILLOT 01/04/09'", ' NULL', ' NULL']] 


But My Ouput file still has the problem.Any Could help me ? 
+0

只是一个想法:你检查你的表定义吗? – jensgram 2009-12-02 08:16:47

+0

我更新了我的queston.Thanks征求意见。 – kn3l 2009-12-02 08:40:19

+0

是的,因为我用法语 – kn3l 2009-12-02 08:47:49

回答

1

请使用.encode("utf-8"),当你写.sql文件了。

打开文件

fileObj = codecs.open("someFile", "r", "utf-8") 

可以说你读它

data=fileOjb.read() 

...做一些数据

open("newfile","w").write(data.encode("utf-8")) 
+0

我更新了我的问题。谢谢。 – kn3l 2009-12-02 08:41:08

+0

我可以假设,你想'Gérant'而不是'G \ xc3 \ xa9rant'在.sql文件中? – YOU 2009-12-02 08:56:35

+0

yes.it会是这样的。 – kn3l 2009-12-02 09:03:22

0
文件.SQL的

喜校验编码也许它不是utf-8!

0

将您的工作数据作为Unicode在Python内部存储(在读取时使用解码),并始终使用编码写出。

在您的实例中,您需要知道数据库的编码以了解正确的输出编码。

+0

是的,因为我用法语。 – kn3l 2009-12-02 08:46:14