huyanmin 发表于 2021-1-25 11:15:35

python 29.4课习题 此题对文件只读方式和写入方式各打开一次,请教按什么顺序关闭...

本帖最后由 huyanmin 于 2021-1-25 11:37 编辑

#对源程序,略改动,报错,找不到出错原因
def filereplace(filename,old_word,new_word):


    with open(filename,encoding='utf-8') as file:
      
      list =[]
      count=0
      for line in file:
            for old_word in line:
                count += line.count(old_word)
                line = line.replace(old_word,new_word)
            list.append(line)
      file.close() #此处改动,源代码不在此位置
            
      decide = input('\n文件%s中共有%d个【%s】\n您确定要把所有的【%s】替换为【%s】吗?\n\
    【YES/NO】:)
                  
      if decide in ['YES','Yes','yes']:
            with open(filename,'w',encoding='utf-8') as file:
                file.writelines(list)
                file.close()
      

filename = input('请输入文件名:')
old-word = input('请输入需要替换的单词或字符:')
new-word = input('请输入新的单词或字符:')

filereplace(filename,old-word,new-word)



#源代码

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)

                  

小伤口 发表于 2021-1-25 11:28:57

你的yes这些相当于变量名了,所以会报错吧 if decide in :
页: [1]
查看完整版本: python 29.4课习题 此题对文件只读方式和写入方式各打开一次,请教按什么顺序关闭...