Skip to main content
 首页 » 编程设计

python之带有德语变音符号的 psycopg2 unicodeencodeerror

2025年05月04日16daizhj

我当前的 python 脚本有问题。

我使用 os.walk 扫描预定义的目录,返回一个列表,其中包含找到的所有图像文件。我通过 psycopg2 将该列表与 postgres 数据库进行比较。

它工作正常,直到我到达名称中带有 german umlaut 的子目录或文件 (äöü) 然后它收到以下错误:

UnicodeEncodeError:'utf-8' 编解码器无法对位置 146-147 中的字符进行编码:不允许代理项

我当前的代码如下所示:

import psycopg2 
import settings 
import os 
 
 
def open_conn(): 
    conn = psycopg2.connect( 
                            user=settings.DB_USER, 
                            password=settings.DB_PW, 
                            host=settings.DB_IP, 
                            port=settings.DB_Port, 
                            database=settings.DB_DB 
                        ) 
    return conn 
 
 
def filterExtensions(file_, extensions_): 
    if file_.lower().endswith(extensions_): 
        return True 
    return False 
 
 
def getFiles(path_, topdown_=False): 
    files_found = [] 
    for root, dirs, files in os.walk(path_, topdown=topdown_): 
        for name in files: 
            files_found.append(os.path.join(root, name)) 
    return files_found 
 
 
for folders_ in settings.FILE_DIR: 
    files_found = getFiles(os.path.join(os.getcwd(), folders_)) 
 
 
conn = open_conn() 
cur = conn.cursor() 
 
 
for file_ in files_found: 
    qs = "SELECT * FROM image_meta WHERE sourcefile = '" + file_ + "';" 
    cur.execute(qs) 
    conn.commit() 

当我到达 cur.execute(qs) 时,我得到了错误。

当我硬编码路径只是为了测试时,它可以完美地工作。

qs = "SELECT * FROM image_meta WHERE sourcefile = '/src/filecrawler/filecrawler/images/original/Grüner_Testordner/IMG_0004.CR2';" 

我在 python3 和 psycopg2 2.8.3 上运行

编辑: 按照 holdenweb 和 frankegoesdown 的指示更改我的代码后,我仍然遇到相同的错误。

  File "test.py", line 42, in <module> 
    cur.execute(qs, (file_,)) 
UnicodeEncodeError: 'utf-8' codec can't encode characters in position 101-102: surrogates not allowed 

我不知道它是否重要,但文件和文件夹是在 mac 上创建的。

请您参考如下方法:

欢迎使用 Stackoverflow。恐怕你构建查询的方法 绝不推荐。

Python 数据库模块允许您使用 parameterized queries ,其中包含 实际数据值的占位符。然后在中提供值本身 作为第二个参数传递给游标的 execute 方法的元组。

psycopg2 使用 pyformat 参数化机制,所以尝试替换 有问题的陈述

qs = "SELECT * FROM image_meta WHERE sourcefile = %s" 
cur.execute(qs, (file_,)) 

这将确保正确构造您的 SQL。如果您仍然遇到问题,它们可能与文件名的编码假设不正确有关。