Python编写从外部文件读取内容生成字典的函数运行出错如何解决
问题排查与修复
你的代码存在3个明确的逻辑错误,以下是逐一说明和修复方案:
- 问题1:执行
file_content = input_file.read()后,文件读取指针已经移动到文件末尾,后续的for line in input_file遍历无法读取到任何内容,这是读取逻辑不生效的核心原因,不需要提前一次性读整个文件的情况下直接删除这行代码即可。 - 问题2:字典赋值逻辑错误,初始化空字典后直接调用
di[read_name].append(read_seq)会触发KeyError(键不存在时无法直接调用append方法),且需求中每个键对应唯一的序列字符串,不需要append操作,直接di[read_name] = read_seq即可。 - 问题3:
input_file.close()写在return语句之后,属于永远不会被执行的死代码,文件资源无法正常释放。更稳妥的方式是使用with上下文管理器自动处理文件的开启和关闭,不需要手动调用close。
修复后的可运行代码如下:
def data(name): di = {} # 使用with上下文管理器自动管理文件生命周期 with open(name, 'r') as input_file: for line in input_file: # 跳过空行避免索引报错 line = line.strip() if not line: continue fields = line.split() read_name = fields[0] read_seq = fields[1] di[read_name] = read_seq return di print(data('sequences.txt'))
运行后将输出{'first': 'AGGCGAA', 'second': 'TTTCGG', 'third': 'GCGCGAA'},完全符合需求。
内容的提问来源于stack exchange,提问作者Vic
相关产品推荐
相关产品推荐

