python - 如何使用 Python 使用 Unicode 编码查找和替换 *.txt 文件中的字符串?

标签 python unicode encoding

我正在尝试将同一文件夹中所有 *.txt 文件中的“FullName”替换为用户输入字符串。 *.txt 文件似乎是 Unicode(当我单击"file"->“另存为”时显示 Unicode)。

每次我运行代码时,它都会用一些不正确的符号替换“全名”(例如,很多਍ഀ਍ഀ和਍ഀ਍䘀甀氀氀一愀洀攀ഀ਍䨀漀恋伥漀猀)碗琀碗漀渀ഀ਍䐀㨀ꀀ㌀ꀀ㠀㠀)。

当我制作一个随机 *.txt 文件并将其另存为 ANSI 或将任何原始文件另存为 ANSI 时,替换工作正常。

有人可以帮我理解这里出了什么问题吗?

fullName = input('Full Name: ')
import glob

fullName = input('Full Name: ')
for f in glob.glob('*.txt'):
    with open(f, 'r') as inputfile:
        newText = inputfile.read().replace('FullName', fullName)
    with open(f, 'w') as outputfile:
        outputfile.write(newText)

Unicode 编码:

Unicode Encoding

更换后的影响:

Aftermaths of replacement

最佳答案

Windows 默认以 UTF-16 格式保存 Unicode,因此请尝试使用 encoding='utf-16' 打开文件:

for f in glob.glob('*.txt'):
    with open(f, 'r', encoding='utf-16') as inputfile:
        newText = inputfile.read().replace('FullName', fullName)
    with open(f, 'w', encoding='utf-16') as outputfile:
        outputfile.write(newText)

关于python - 如何使用 Python 使用 Unicode 编码查找和替换 *.txt 文件中的字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55324958/

相关文章:

python - 使用 Python 向 Word 文档添加页码

javascript - 如何同时验证中文(unicode)和英文名称?

perl - 在 Perl 中打印到文件与打印到 shell

MySQL:问号而不是符号

python - `Ctrl + C` 当加载使用信号处理程序的共享库时,Python 中的 input() 不起作用

python - 根据单元格值分解数据帧

python - 在 Python 或 PIL 中是否有一种简单的方法来调整/扩展仅包含零的图像大小?

python - 更正在 TravisCI 上的 2.7.10 应用程序中打印 unicode 字符时的 unicode 错误

c# - 来自字符串的 MemoryStream - 关于要使用的编码的混淆

ruby - ruby 的正确 utf-8 编码注释行是什么?