2013-09-27 123 views
0

由于£标志位于我的字符串/列表中,因此我遇到了将数据写入文件的问题。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")) 
+0

阅读:http://nedbatchelder.com/text/unipain.html –

+0

编辑距离相当明显原来的问题。也许你可以开一个新的问题。 –

回答

3

你需要写之前将Unicode字符串编码:

dfile.write('\n'.join(x).encode("UTF-8")) 

或者,您在Python 2.x中使用使用codecs.open(),因此在打开文件时将编码作为参数传递:

import codecs 

with codecs.open('test.txt', 'w', encoding="UTF-8") as dfile: 
    dfile.write('\n'.join(x)) 

相关:

+0

工程很好,但是折扣单上的'£'出现为:¢35.00,因为它接收2作为ascii的一部分... – Ryflex

+1

我开始推荐'io.open()'而不是'codecs.open ()',因为它在Python 3上继续工作。API与'codecs.open()'很相似,但提供更多选项,包括换行处理。 –

+0

@MartijnPieters。哦!请看看它。不知道这一点。 –