|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
def replace_string(old, new):
f1 = open(file_name)
count = 0
for each_line in f1:
if old in each_line:
count += 1
print('文件%s中共有%s【%s】\n' % (file_name, count, new))
print('你确定要把所有的【%s】替换为【%s】\n' % (new, old))
select = input('【YES/NO】:')
if select == 'YES':
f2 = open(file_name, 'w')
f2.replace(old, new, count)
f2.close()
f1.close()
file_name = input('请输入文件名:')
old = input('请输入需要替换的单词或字符:')
new = input('请输入新的单词或字符:')
replace_string(old, new,)
本帖最后由 jackz007 于 2020-12-28 23:48 编辑
文件编码错误,当前缺省编码 'GBK' 无法解码文件中的中文字符。这个文件中的中文字符应该是采用了 'UTF-8' 的字符编码,打开文件的语句应该加上 encoding 选项。
- def replace_string(old, new):
- f1 = open(file_name , encoding = 'UTF-8') # 修改这一句
复制代码
|
|