0

£由于我的字符串/列表中有符号,我在将数据写入文件时遇到问题。

例如,在我下面的代码中,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"))
4

1 回答 1

3

You need to encode the unicode string before writing:

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

Alternatively, you use use codecs.open() in Python 2.x, thus passing the encoding as the argument while opening file:

import codecs

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

Related:

于 2013-09-27T20:17:56.257 回答