打开文本文件时出现Unicode错误
我有一个可能很简单的问题。不过,我刚开始使用Python,这让我感到很困惑。我正在按照一本书的说明,想打开一个简单的文本文件。
我用的代码是:
import sys
try:
d = open("p0901aus.txt" , "W")
except:
print("Unsucessfull")
sys.exit(0)
但是我要么收到消息说我无法打开这个文档,要么弹出一个窗口显示:
(unicode错误) 'unicodeescape' 编解码器无法解码位置2-4的字节:\UXXXXXXXX转义序列被截断
我完全不知道问题出在哪里。我尝试过用不同的编码保存文档,也试过不同的路径……结果总是同样的问题。
有没有人能帮帮我?
非常感谢,
乔治
附:我使用的是Windows Vista
3 个回答
import csv
data = csv.reader(open('c:\x\list.csv' ))
for row in data:
print(row)
print('ready')
出现了一个错误,内容是“(unicode error)'unicodeescape' 编解码器无法解码位置 2-4 的字节:\xXX 转义序列不完整”。
你可以试试用 c:\\x\\list.csv
代替 c:\x\list.csv
。
这段代码是用 Python 3 写的。
把这个改成
# for Python 2.5+
import sys
try:
d = open("p0901aus.txt","w")
except Exception, ex:
print "Unsuccessful."
print ex
sys.exit(0)
# for Python 3
import sys
import codecs
try:
d = codecs.open("p0901aus.txt","w","utf-8")
except Exception as ex:
print("Unsuccessful.")
print(ex)
sys.exit(0)
注意,W是区分大小写的。我不想一下子把所有的Python语法都告诉你,但知道怎么显示出现了什么错误是很有用的,这是一种方法。
另外,你现在是以写的方式打开文件,而不是读的方式。这是你想要的吗?
如果已经有一个叫做p0901aus.txt的文件,并且你想读取它,可以这样做:
#for Python 2.5+
import sys
try:
d = open("p0901aus.txt","r")
print "Awesome, I opened p0901aus.txt. Here is what I found there:"
for l in d:
print l
except Exception, ex:
print "Unsuccessful."
print ex
sys.exit(0)
#for Python 3+
import sys
import codecs
try:
d = codecs.open("p0901aus.txt","r","utf-8")
print "Awesome, I opened p0901aus.txt. Here is what I found there:"
for l in d:
print(l)
except Exception, ex:
print("Unsuccessful.")
print(ex)
sys.exit(0)
当然,你也可以在Python 2.5中使用codecs,如果这样做,你的代码质量会更高(“正确”)。Python 3似乎把字节顺序标记当作一种奇怪的东西,或者说是一些杂音,这让人有点失望。
(unicode错误) 'unicodeescape' 编解码器无法解码位置2-4的字节:\UXXXXXXXX转义序列不完整
这通常意味着你尝试读取的文件编码方式和open()函数所期望的不同。open()函数通常期待某种Unicode编码(最有可能是UTF-8或UTF-16),但你的文件并不是这种编码。
通常情况下,不建议直接使用open()来读取文本文件,因为如果不指定编码,就无法正确读取文本文件(除非它是纯ASCII编码)。
建议使用codecs模块来处理:
import codecs
fileObj = codecs.open( "someFile", "r", "utf-8" )
u = fileObj.read() # Returns a Unicode string from the UTF-8 bytes in the file