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

调用get_info返回None而非List触发TypeError问题求助

Python TypeError问题:get_info返回None导致下标访问失败

问题说明

调用get_info(name)时返回None而非预期的列表,触发错误TypeError: 'NoneType' object is not subscriptable。change_job函数用于修改data.txt中指定人员的职位,但get_info的判断逻辑错误——将字符串name直接与分割后的列表lines[num]比较,导致匹配失败时返回None。空文件测试无报错,但主程序运行时触发上述错误,需修复get_info使其正确返回列表。

原函数代码

def change_job(name, newjob):
    with open('data.txt', 'r') as file:
        lines = file.readlines()
    with open('data.txt', 'w') as file:
        info = get_info(name) # Here I get type None
        for line in lines:
            if name in line:
                file.write(f"{info[0]} - {info[1]} - {newjob} - {info[3]}")
            else:
                file.write(line)


def get_info(name):
    with open('data.txt', 'r') as file:
        lines = [line.split(" - ") for line in file]
        num = 0
        for i in lines:
            if name == lines[num]:
                return lines[num]
            num += 1

空文件测试代码

import data

info = data.get_info("Johny")

print(info)
print(type(info))

报错信息

Traceback (most recent call last):
  File "C:\PyProjects\Payment\main.py", line 70, in <module>
    data.change_job(wname, newjob) # wname and newjob are written by user
  File "C:\PyProjects\Payment\data.py", line 34, in change_job
    file.write(f"{info[0]} - {info[1]} - {newjob} - {info[3]}")
TypeError: 'NoneType' object is not subscriptable

修复方案

1. 修复get_info的判断逻辑

get_info中错误地将字符串name与分割后的整个列表比较,实际应该拿name和列表中的姓名字段(假设是第一个元素)对比,同时处理换行符和空白字符:

def get_info(name):
    target_name = name.strip()
    with open('data.txt', 'r') as file:
        for line in file:
            line = line.strip()
            if not line:
                continue  # 跳过空行
            parts = line.split(" - ")
            # 对比第一个字段(姓名),去除前后空白
            if parts[0].strip() == target_name:
                # 移除最后一个元素可能带的换行符
                if parts[-1].endswith('\n'):
                    parts[-1] = parts[-1].rstrip('\n')
                return parts
    # 未找到时返回空列表,避免返回None导致后续报错
    return []

2. 优化change_job的容错处理

在change_job中增加对info的判断,避免空列表时下标访问错误:

def change_job(name, newjob):
    with open('data.txt', 'r') as file:
        lines = file.readlines()
    with open('data.txt', 'w') as file:
        info = get_info(name)
        for line in lines:
            stripped_line = line.strip()
            if not stripped_line:
                file.write(line)
                continue
            if name.strip() in stripped_line:
                if len(info) >=4: # 确保info有足够元素
                    file.write(f"{info[0]} - {info[1]} - {newjob} - {info[3]}\n")
                else:
                    # 数据格式异常时保留原行
                    file.write(line)
            else:
                file.write(line)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 12:00:58