文件修改 核心5步
1、以读的模式打开原文件,产生句柄f1
2、以写的模式打开一个新文件,产生句柄f2
3、读取原文件的内容并将原文件需要替换的内容修改写入到新文件
4、删除原文件
5、把新文件重名了成原文件
import os
# 1、以读的模式打开原文件,产生句柄f1
# 2、以写的模式打开一个新文件,产生句柄f2
with open('1.txt', encoding='utf-8', mode='r') as f1, \
        open('2.txt', encoding='utf-8', mode='w') as f2:
    # 3、读取原文件的内容并将原文件需要替换的内容修改写入到新文件
    for old_data in f1:
        new_data = old_data.replace('7777', '6666')
        f2.write(new_data)
# 4、删除原文件
os.remove('1.txt')
# 5、把新文件重名了成原文件
os.rename('2.txt', '1.txt')

 

import os


def change(file_name, old_content, new_content):
# 最后一个单引号前有两个\\是为了防止\与单引号发生转义
    file_name = r'E:\pythonProject\OldBoy_learn\\' + file_name
    with open(file_name, 'r', encoding='utf-8') as f1, \
            open(file_name + '.bak', 'w', encoding='utf-8') as f2:
        for old_line in f1:
            new_line = old_line.replace(old_content, new_content)
            f2.write(new_line)
    os.remove(file_name)
    os.rename(file_name + '.bak', file_name)


f_name = input('请输入文件名:')
o_content = input('请输入要修改的内容:')
n_content = input('请输入修改后的内容:')
change(f_name, o_content, n_content)

 

相关文章:

  • 2021-06-24
  • 2022-12-23
  • 2021-07-02
  • 2021-08-22
  • 2021-09-13
  • 2021-07-31
  • 2022-02-16
  • 2022-02-27
猜你喜欢
  • 2021-07-26
  • 2021-06-10
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-11-06
相关资源
相似解决方案