|
|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
编码错误一般是什么原因引起的?
Python 3.6.4 (v3.6.4:d48eceb, Dec 19 2017, 06:54:40) [MSC v.1900 64 bit (AMD64)] on win32
Type "copyright", "credits" or "license()" for more information.
>>>
RESTART: C:\Users\Administrator\Desktop\Python_test\Replace.py
请输入文件名:something.txt
请输入需要替换的单词或字符:愿
请输入新的单词或字符:希望
Traceback (most recent call last):
File "C:\Users\Administrator\Desktop\Python_test\Replace.py", line 28, in <module>
file_replace(file_name, rep_word, new_word)
File "C:\Users\Administrator\Desktop\Python_test\Replace.py", line 8, in file_replace
for eachline in f_read:
UnicodeDecodeError: 'gbk' codec can't decode byte 0x80 in position 20: illegal multibyte sequence
>>>
下面是代码:
def file_replace(file_name, rep_word, new_word):
f_read = open(file_name)
content = []
count = 0
for eachline in f_read:
if rep_word in eachline:
count = eachline.count(rep_word) #count感觉应该用这个
eachline = eachline.replace(rep_word, new_word)
content.append(eachline)
decide = input('\n文件 %s 中共有%s个[%s]\n您确定要把所有的[%s]替换为[%s]吗?\n[YES/NO]:' \
% (file_name, count, rep_word, rep_word, new_word))
if decide in ['YES', 'Yes', 'yes']:
f_write = open(file_name, 'w')
f_write.writelines(content)
f_write.close()
f_read.close()
file_name = input('请输入文件名:')
rep_word = input('请输入需要替换的单词或字符:')
new_word = input('请输入新的单词或字符:')
file_replace(file_name, rep_word, new_word)
编码问题,你打开文件时加个encoding='gbk’试试,Python一般采用‘utf-8’方式编码和解码,写入也加入
不行就全改encoding=‘utf-8’试试
|
|