用于UTF-16-LE文件的Python字符串替换

Sta*_*tan 2 python string

Python 2.6

使用Python string.replace()似乎不适用于UTF-16-LE文件.我想到了两种方式:

  1. 找到一个可以处理Unicode字符串操作的Python模块.
  2. 将目标Unicode文件转换为ASCII,使用string.replace(),然后将其转换回来.但我担心这可能导致数据丢失.

社区能否建议我解决这个问题的好方法?谢谢.

编辑:我的代码看起来像这样:

infile = open(inputfilename)
for s in infile:
 outfile.write(s.replace(targetText, replaceText))
Run Code Online (Sandbox Code Playgroud)

看起来for循环可以解析正确的行.我在这里犯了什么错吗?

EDIT2:

我已经阅读了Python Unicode教程并尝试了下面的代码,并使其工作.但是,只是想知道是否有更好的方法来做到这一点.有人可以帮忙吗?谢谢.

infile = codecs.open(infilename,'r', encoding='utf-16-le')

newlines = []
for line in infile:
    newlines.append(line.replace(originalText,replacementText))

outfile = codecs.open(outfilename, 'w', encoding='utf-16-le')
outfile.writelines(newlines)
Run Code Online (Sandbox Code Playgroud)

我需要关闭infile或outfile吗?

Joh*_*hin 8

您没有Unicode文件.没有这样的东西(除非你是NotePad的作者,它混淆了"Unicode"和"UTF-16LE").

请阅读Unicode Python Unicode HOWTOJoel.

更新我很高兴建议阅读帮助你.这是代码的更好版本:

infile = codecs.open(infilename,'r', encoding='utf-16-le')
outfile = codecs.open(outfilename, 'w', encoding='utf-16-le')
for line in infile:
    fixed_line = line.replace(originalText,replacementText)
    # no need to save up all the output lines in a list
    outfile.write(fixed_line)
infile.close()
outfile.close()
Run Code Online (Sandbox Code Playgroud)

完成后立即释放资源(例如关闭文件)总是一个好习惯.更重要的是,对于输出文件,在关闭文件之前通常不会更新目录.

阅读"with"语句,了解更好的文件处理实践.