You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python使用with语句复制文件后如何在同程序中打开新文件完成替换统计

核心解决逻辑
  • 经with语句管理的文件对象执行完块逻辑后会自动关闭,不可直接复用,需要操作对应文件时,重新调用open()方法传入对应文件路径即可。你已经将新文件的名称存在变量b中,路径为b+".txt",直接用该路径重新打开即可
  • 你现有代码还存在多处语法错误、缺少替换计数逻辑,修正后的可运行代码如下:
# 读取源文件和目标文件名
filename = input("Sisesta tekstifaili nimi: ")
new_file_name = input("Sisesta uue tekstifaili nimi: ") + ".txt"

# 第一步:复制源文件内容到新文件
with open(filename, "r", encoding="utf-8") as input_f:
    with open(new_file_name, "w", encoding="utf-8") as output_f:
        for line in input_f:
            output_f.write(line)

# 替换映射规则
replace_map = {'hello':'tere', 'Hello':'Tere'}
replace_count = 0
processed_lines = []

# 第二步:重新打开新文件读取内容,完成替换计数
with open(new_file_name, "r", encoding="utf-8") as in_f:
    for line in in_f:
        for src, target in replace_map.items():
            # 统计当前行待替换词汇出现次数,累加到总计数
            replace_count += line.count(src)
            line = line.replace(src, target)
        processed_lines.append(line)

# 第三步:将替换后的内容写回新文件
with open(new_file_name, "w", encoding="utf-8") as out_f:
    for line in processed_lines:
        out_f.write(line)

# 输出替换总次数
print(f"总替换次数:{replace_count}")
额外优化说明

如果你不需要分开执行复制和替换逻辑,也可以在第一次复制内容的时候直接完成替换和计数,不需要重复打开文件,执行效率更高:

filename = input("Sisesta tekstifaili nimi: ")
new_file_name = input("Sisesta uue tekstifaili nimi: ") + ".txt"
replace_map = {'hello':'tere', 'Hello':'Tere'}
replace_count = 0

with open(filename, "r", encoding="utf-8") as input_f:
    with open(new_file_name, "w", encoding="utf-8") as output_f:
        for line in input_f:
            for src, target in replace_map.items():
                replace_count += line.count(src)
                line = line.replace(src, target)
            output_f.write(line)

print(f"总替换次数:{replace_count}")

内容的提问来源于stack exchange,提问作者RCWZX

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 21:27:03