2010-11-11 60 views
0

我正在尝试编写一个用于从保存在文件中的存档列表中写入sqlite表的小脚本。到目前为止的代码是这样的:python x64中的编码问题

import os import _sqlite3 import sys 

print sys.path[0] mydir = sys.path[0] print (mydir) def listdir(mydir): 
    lis=[] 
    for root, dirs, files in os.walk(mydir): 
     for name in files: 
      lis.append(os.path.join(root,name)) 
    return lis 
    filename = "list.txt" print ("writting in %s" % filename) file = open(filename, 'w') for i in listdir(mydir): 
    file.write(i) 
    file.write("\n") file.close() 

con = 
_sqlite3.connect("%s/conection"%mydir) c=con.cursor() 

c.execute(''' drop table files ''') c.execute('create table files (name text, other text)') file = open(filename,'r') for line in file : 
    a = 1 
    for t in [("%s"%line, "%i"%a)]: 
     c.execute('insert into files values(?,?)',t) 
     a=a+1 c.execute('select * from files') print c.fetchall() con.commit() c.close() 

当我运行得到如下:

Traceback (most recent call last): File "C:\Users\josh\FORGE.py", line 32, in <module> 
    c.execute('insert into files values(?,?)',t) ProgrammingError: You must not use 8-bit bytestrings unless you use a text_factory that can interpret 8-bit bytestrings (like text_factory = str). It is highly recommended that you instead just switch your application to Unicode strings. 

从来就试图与Unicode的()内置函数,但仍不需额外的工作,他说,他不能解码字符0xed或什么的。

我知道问题出在列表字符串的编码上,但是我找不到一种方法将它们放在正确的位置。有任何想法吗?提前致谢!

+1

http://farmdev.com/talks/unicode/ – 2010-11-11 20:17:37

回答

1

(零)。请重新格式化您的代码

  1. for line in file:后这样做line = line.decode('encoding-of-the-file'),与编码是类似utf-8,或iso-8859-1 - 你必须知道你的输入编码

    如果你不知道编码或者不关心干净的解码,你可以猜出最可能的编码,并做一个line.decode('uft-8', 'ignore'),省略所有不可解码的字符。此外,还可以使用'replace',它与“Unicode替换字符”替换这些字符(\ ufffd)

  2. 使用内部和通信期间与数据库unicode对象,例如u'this is unicode'

(3)。不要使用file变量名

也看这里:Best Practices for Python UnicodeDecodeError

+0

line.decode解决了这个问题,谢谢! – Choice 2010-11-12 01:31:15

+0

也,我改变了文件名,完全忘了它被保留,谢谢。 – Choice 2010-11-12 01:32:05