Python sqlite3.ProgrammingError:除非使用可解释8位字节串的te
发布时间:2020-12-20 11:38:14 所属栏目:Python 来源:网络整理
导读:我正在编写一个脚本,以递归方式扫描目录并将它们存储在字典中,该字典是列表的集合.这个燕鸥列表包含具有文件名和文件大小的列表.此文件名可能包含UTF-8字符,如下所示. ['test.rus (xd0xa5xd0xb5xd0xbbxd1x8cxd1x88xd0xb8).srt',23930]test.rus (
|
我正在编写一个脚本,以递归方式扫描目录并将它们存储在字典中,该字典是列表的集合.这个燕鸥列表包含具有文件名和文件大小的列表.此文件名可能包含UTF-8字符,如下所示.
['test.rus (xd0xa5xd0xb5xd0xbbxd1x8cxd1x88xd0xb8).srt',23930] test.rus (Хельши).srt 现在,在尝试将数据插入数据库时??,我收到如下错误 Traceback (most recent call last):
File "filedup.py",line 267,in <module>
read_file_directory(directory)
File "filedup.py",line 118,in read_file_directory
(values[i][0],each,values[i][1]))
sqlite3.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.
执行该操作的功能如下 from collections import defaultdict
dirDict = defaultdict(list)
def read_file_directory(path):
global dirDict
logger.debug("Path being scanned %s" %path)
fileStats = []
for root,subFolders,files in os.walk(path):
for file_name in files:
fileStats = []
fileStats.insert(0,file_name)
fileSize = os.path.getsize(os.path.join(root,file_name))
fileStats.insert(1,fileSize)
dirDict[root].append(fileStats)
#Insert the data in DB
cursor = dbHandler.cursor()
keys = dirDict.keys()
for each in keys:
values = dirDict[each]
print values
for i in xrange(len(values)):
print values[i]
print values[i][0]
print values[i][1]
fileName = values[i][0]
fileSize = values[i][1]
cursor.execute("insert or ignore into master
(FileName,FilePath,FileSize) values(?,?,?)",
(values[i][0],values[i][1]))
logger.debug("Insert data for %s,%s,%s" %(values[i][0],values[i][1]))
现在,当我试图学习Python时,我没有得到如何解决这个问题.我正在使用的Python版本如下所示 $python Python 2.7.6 (default,Mar 22 2014,22:59:56) [GCC 4.8.2] on linux2 所以任何想法如何解决当前版本的Python,因为我正在寻找通用修复程序,以便它甚至可以在更高版本上工作. 解决方法
sqlite异常建议您切换到unicode字符串,因此您应该这样做.
Python的目录列表函数如os.walk有一个curious property;当给定普通字符串时,它们将返回正常字符串,并在给定unicode字符串时返回unicode字符串.因此,在代码中使用os.walk(path)时,应确保path是unicode字符串. 为此,您可以使用unicode()函数显式转换为unicode,例如在调用os.walk之前编写path = unicode(path). 此外,您需要在代码中调用cursor.commit()来实际写入数据库.在完成所有文件名的循环后调用它应该就足够了. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
