由于£
标志位于我的字符串/列表中,因此我遇到了将数据写入文件的问题。Python字符串/列表符号£符号写入文件失败?
例如在我下面的代码中,x
由一系列来自各种正则表达式搜索,匹配,下属和通用修剪/分割的附加内容创建。
# -*- coding: utf-8 -*-
x = [u'Loc ', u'352', '1', '51', '3D2', u'Student Total \xa3540.00', u'Discount \xa235.00', '\n', u'Rec ', u'352', '2', '51', '5S1', u'Student Total \xa3540.00', u'Discount \xa235.00', '\n']
with open('test.txt','w') as dfile:
dfile.write('\n'.join(x)) # UnicodeEncodeError: 'ascii' codec can't encode character u'\xa3' in position 71: ordinal not in range(128)
dfile.write(x) # TypeError: expected a character buffer object
我想写x到文件,所以会出现这样的:
Loc
352
1
51
3D2
Student Total £3540.00
Discount £235.00
Rec
352
2
51
5S1
Student Total £3540.00
Discount £235.00
任何人都知道我该怎么做我想达到什么目的?
编辑
我现在不能让它来比较,如果它是不同的,那么保存...
with open('test.txt','r') as dfile:
dfiler = dfile.read()
dfiler = dfiler.decode("UTF-8")
if dfiler == x:
print "same, no need to save"
else:
with open('test.txt','w') as result_end_datafile:
dfile.write('\n'.join(x).encode("UTF-8"))
阅读:http://nedbatchelder.com/text/unipain.html –
编辑距离相当明显原来的问题。也许你可以开一个新的问题。 –