Python中文件处理中的try和except如何工作?
我很好奇在Python中Try和Except是怎么工作的,因为我遇到了这个错误:
def for_file(data):
open_file = file('data.txt', 'w')
try:
open_file.write(data)
except:
print 'This is an error!'
open_file.close()
输出: 这是一个错误!
def for_file(data):
try:
open_file = file('data.txt', 'w')
open_file.write(data)
print 'Successful!'
except:
print 'This is an error!'
open_file.close()
输出: 成功了!
这怎么可能呢?
错误: 'ascii' 编码无法编码位置15-16的字符:序号不在范围(128)内
我收到了Unicode格式的数据,我该怎么办呢?
3 个回答
0
你可能需要打印出错误信息,这样才能弄清楚问题出在哪里:
def for_file(data):
open_file = file('data.txt', 'w')
try:
open_file.write(data)
except Exception as e:
print 'This is an error!'
print e
open_file.close()
1
你遇到了一个类型错误。写入文件时,'data' 需要是字符串或者缓冲区。如果你不传递字符串或缓冲区给你的第二个函数,它也会出问题(我试过传递一个 2,结果都不行)。下面的代码是可以正常工作的。
def for_file(data):
open_file = file('data.txt', 'w')
try:
open_file.write(str(data))
print "Success!"
except:
import traceback; traceback.print_exc() #I used this to find the error thrown.
print 'This is an error!'
open_file.close()
3
要把unicode数据写入文件,可以使用 codecs.open()
这个方法:
import codecs
with codecs.open('data.txt', 'w', 'utf-8') as f:
f.write(data)