|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
又要劳烦各位前辈, 此题的答案我读的明白, 把文件内容 拆出, 替换关键字,组成新的列表文件,在选择确定修改后, 覆盖原有文件。 这里面有一点没太明白, 就是替换这步为何要在 用户选择 是否替换之前做?
还有 我写的 方法 在运行中 报错, 但是没太看明白 报错的原因何在,说 IO OPERATION UNSUPPORTED,
小甲鱼老师答案:
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') #用重新拼合内容造新文件用’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)
========================================================================================
我的 代码
file=input('请输入文件名:')
repword=input('请输入需要替换的单词或字符:')
newword=input('请输入新的单词或字符:')
fread=open(file)
count=0
for eachline in fread:
if repword in eachline:
count+=1
decide=input('threre are %s words in file %s need to be chaged \n do u need to change all? [y]or[n]:' \
%(count,file))
if decide in['y','y']:
fwrite=open(file,'a')
for eachline in fwrite:
eachline=eachline.replace(repword,newword)
fwrite.writelines(eachline)
fwrite.close()
运行后 ,
Traceback (most recent call last):
File "D:/Python33/29kezuoyue 4 ti.py", line 15, in <module>
for eachline in fwrite:
io.UnsupportedOperation: not readable
很好奇这个 not readable 是 怎么引发的, 多谢指导
本帖最后由 逃兵 于 2021-1-23 11:50 编辑
fwrite=open(file,'a') 这是附加写,但是不能读,这个就是not readable的原因
fwrite=open(file,'a+') 是附加可读写
但是指针会在结尾,也读不出来
小甲鱼的方式是开辟一个临时的内存(比如列表)来存取你的数据,然后再以覆盖写入的方式打开文件,导入临时数据,覆盖掉原始数据,达成替换字符的目的
yes 和 no是来判断是否写入的
数据处理在yes no的判断之前完成是因为 为了查看有几处时 已经遍历过文件,在做这一部的同时就可以将数据处理完了,之后不用再次遍历数据了
|
-
|