Python sqlite3.ProgrammingError:除非使用能够解释8位bytestrings的文本工厂,否则不能使用8位bytestrings

2024-06-16 11:34:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在编写一个脚本,它递归地扫描一个目录并将它们存储在一个字典中,字典是一个列表的集合。terns中的这个列表包含有文件名和文件大小的列表。此文件名可以包含UTF-8字符,如下所示。

['test.rus (\xd0\xa5\xd0\xb5\xd0\xbb\xd1\x8c\xd1\x88\xd0\xb8).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], each, values[i][1]))
            logger.debug("Insert data for %s, %s, %s" %(values[i][0], each, values[i][1]))

现在,当我试图学习Python时,我不知道如何解决这个问题。下面给出了我正在使用的Python版本

$ python
Python 2.7.6 (default, Mar 22 2014, 22:59:56) 
[GCC 4.8.2] on linux2

所以我在寻找通用的修复方法,以便它可以在更高的版本上工作时,如何使用当前版本的Python进行修复。 我还注意到,由于这个错误,没有一个数据被插入到数据库中。因此,如何确保即使某些操作导致错误,也可以将以前的数据插入到数据库中。


Tags: 数据pathin数据库列表for错误directory
2条回答

尝试更改行:

fileStats.insert(0, file_name)

fileStats.insert(0, file_name.decode('utf8'))

sqlite异常建议您切换到unicode字符串,因此应该这样做。

Python的目录列表函数如os.walk有一个curious property;当给定普通字符串时,它们将返回普通字符串,当给定unicode字符串时,它们将返回unicode字符串。因此,在代码中使用os.walk(path)时,应该确保path是一个unicode字符串。

为此,可以使用unicode()函数显式转换为unicode,例如在调用os.walk之前写入path = unicode(path)

另外,您需要在代码中调用cursor.commit(),才能真正写入数据库。在完成所有文件名的循环之后调用一次就足够了。

相关问题 更多 >