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

Python脚本通过参数修改文件行时遇TypeError问题求助

问题:修改文件指定行的Python脚本报错TypeError: list indices must be integers or slices, not str

我正在编写一个通过命令行参数修改文件指定行的Python程序,但运行时出现上述错误,脚本代码如下:

import os
import sys
from pathlib import Path

pathh = os.path.basename(__file__)
pathhh = pathh.replace("py", "exe")
path_to_file = f'{sys.argv[1]}'
path = Path(path_to_file)

if path.is_file():
    if len(sys.argv) > 1:
        def replace_line(file_name, line_num, text):
            lines = open(file_name, 'r').readlines()
            lines[line_num] = text
            out = open(file_name, 'w')
            out.writelines(lines)
            out.close()
    
    my_list = [f'{sys.argv[1]}', f'{sys.argv[2]}', f'{sys.argv[3]}']
    my_str = '0'
    my_str2 = '1'
    my_str3 = '2'
    result = my_list[int(my_str)]
    result1 = my_list[int(my_str2)]
    result2 = my_list[int(my_str3)]
    replace_line(f'{result}', f'{result1}', f'{result2}')
else:
    print(f"Usage: {pathh} <File> <LINE> <TOEDIT>")
    print("This program was made by CookieYT#9267")
else:
    print(f"Usage: {pathh} <File> <LINE> <TOEDIT>")
    print("This program was made by CookieYT#9267")

错误原因

报错核心是调用replace_line时传入的line_num是字符串类型(来自sys.argv[2]),而列表lines的索引必须是整数,直接用字符串索引触发TypeError。此外代码还有其他问题:

  • 函数replace_line嵌套在if块内,存在作用域和规范问题
  • 文件操作未用with语句,有资源泄漏风险
  • 参数校验顺序错误,未先检查参数数量,参数不足时会直接崩溃
  • 冗余的列表和字符串转换完全没必要,徒增复杂度

修复后的代码

import sys
from pathlib import Path

def replace_line(file_name, line_num, text):
    # 用with语句自动管理文件资源,无需手动关闭
    with open(file_name, 'r') as f:
        lines = f.readlines()
    # 校验行号是否在有效范围内
    if 0 <= line_num < len(lines):
        lines[line_num] = text + '\n'  # 补充换行符,避免替换后丢失行结构
        with open(file_name, 'w') as f:
            f.writelines(lines)
    else:
        print(f"错误:行号{line_num+1}超出文件行数范围(文件共{len(lines)}行)")

def main():
    script_name = Path(__file__).name
    # 先检查参数数量:脚本名+文件路径+行号+替换文本,共4个参数
    if len(sys.argv) != 4:
        print(f"Usage: {script_name} <File> <LINE> <TOEDIT>")
        print("This program was made by CookieYT#9267")
        return
    
    file_path = Path(sys.argv[1])
    if not file_path.is_file():
        print(f"错误:文件 {file_path} 不存在或不是有效文件")
        return
    
    try:
        # 将用户输入的1起始行号转为代码需要的0起始索引
        line_num = int(sys.argv[2]) - 1
        text = sys.argv[3]
        replace_line(file_path, line_num, text)
        print("修改成功")
    except ValueError:
        print("错误:行号必须是整数")

if __name__ == "__main__":
    main()

关键修改说明

  • 把replace_line移到全局作用域,代码结构更清晰
  • 用with语句处理文件,自动释放资源
  • 先校验参数数量,避免参数不足时的索引错误
  • 将行号字符串转为整数,并适配用户习惯的1起始行号
  • 增加行号有效性检查,防止越界报错
  • 移除冗余的列表和字符串转换逻辑
  • 捕获非整数行号的输入异常,提升程序健壮性

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 15:25:17