Python修改文件编码方案报错:NameError: unicode未定义
解决Python文件编码转换中的
NameError: name 'unicode' is not defined问题 看起来你是在Python 3环境下用了Python 2的语法,这就是报错的核心原因!
问题拆解
unicode()是Python 2专属的函数,用来把字节串转为Unicode字符串,但Python 3里已经移除了这个函数——因为Python 3的str类型本身就是Unicode编码的字符串,不需要额外调用这个方法。- 另外你打开源文件时没指定编码,程序会用系统默认编码读取,这大概率和你预期的
latin-1编码不符,容易引发乱码或读取异常。
修正后的代码(Python 3兼容版本)
推荐用更安全的with语句管理文件(它会自动帮你关闭文件,避免资源泄漏):
source_encoding = "latin-1" target_encoding = "utf-8" # 指定latin-1编码打开源文件,读取内容 with open(r'C:\Users\chsafouane\Desktop\saf.txt', encoding=source_encoding) as source: content = source.read() # 指定utf-8编码写入目标文件 with open(r'C:\Users\chsafouane\Desktop\saf2.txt', "w", encoding=target_encoding) as target: target.write(content)
代码细节解释
- 明确指定文件编码:打开源文件时通过
encoding参数指定用latin-1读取,确保读取到的内容是正确的Unicode字符串(Python 3的str)。 - 自动完成编码转换:写入目标文件时指定
utf-8编码,Python会自动把Unicode字符串转换成utf-8编码的字节写入文件,不需要手动调用encode()。 - with语句的优势:不用手动写
close()方法,文件会在代码块结束后自动关闭,避免忘记关闭文件导致的资源占用问题。
如果想更直观地理解编码转换的底层逻辑,也可以手动处理字节串和Unicode的转换:
source_encoding = "latin-1" target_encoding = "utf-8" # 以二进制模式读取源文件,得到字节串 with open(r'C:\Users\chsafouane\Desktop\saf.txt', 'rb') as source: byte_content = source.read() # 字节串解码为Unicode字符串 unicode_content = byte_content.decode(source_encoding) # Unicode字符串编码为utf-8字节串 target_byte_content = unicode_content.encode(target_encoding) # 二进制模式写入目标文件 with open(r'C:\Users\chsafouane\Desktop\saf2.txt', 'wb') as target: target.write(target_byte_content)
内容的提问来源于stack exchange,提问作者chsafouane
相关产品推荐
相关产品推荐

