我正在尝试将同一文件夹中所有 *.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 编码:
更换后的影响:
最佳答案
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/