You need to enable JavaScript to run this app. Python3 如何编写脚本修改外部py文件的指定内容?
优惠活动
大模型
产品
解决方案
定价
更多

Python3 如何编写脚本修改外部py文件的指定内容?

Python3 实现strings.py内容替换方案

完全适配Python3.x环境,不需要改造旧版本代码逻辑,直接就能运行。

基础测试版本(适配当前测试场景)

将以下代码保存为rewrite.py,和strings.py放在同一文件夹下:

# 配置替换规则
target_file = "strings.py"
old_str = "2"
new_str = "5"

# 读取原文件全部内容
with open(target_file, "r", encoding="utf-8") as f:
    content = f.read()

# 执行替换
replaced_content = content.replace(old_str, new_str)

# 将内容写回文件(覆盖原有内容)
with open(target_file, "w", encoding="utf-8") as f:
    f.write(replaced_content)

执行命令:python rewrite.py
运行完成后打开strings.py,就能看到内容已经变成1、5、3。

精准匹配版本(避免误替换,适合后续正式功能使用)

如果后续使用时不需要替换文件里其他位置的2(比如文件中存在"12"、"20"这类带2的内容,不需要改动),就用按行匹配的逻辑,只替换整行内容为2的行:

# 配置替换规则
target_file = "strings.py"
target_line = "2"
replacement_line = "5"

# 按行读取文件内容
with open(target_file, "r", encoding="utf-8") as f:
    lines = f.readlines()

# 逐行匹配替换
new_lines = []
for line in lines:
    # 去掉行尾换行符、空白后再匹配,避免格式问题导致匹配失败
    if line.strip() == target_line:
        new_lines.append(line.replace(target_line, replacement_line))
    else:
        new_lines.append(line)

# 写回文件
with open(target_file, "w", encoding="utf-8") as f:
    f.writelines(new_lines)

新手注意事项

  • 两个文件必须放在同一目录,否则会抛出FileNotFoundError,需要在代码里把target_file改成文件的完整绝对路径(比如Windows下的D:\code\strings.py,macOS/Linux下的/home/xxx/code/strings.py)
  • 所有open()操作必须加encoding="utf-8"参数,避免Windows默认GBK编码导致的乱码、报错问题
  • 写回文件是覆盖模式,测试前可以先备份原文件,避免操作失误丢失原有内容

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.23 20:15:10