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

Python读取文件函数返回空字典,如何修复该问题?

修复读取价格文件后输出空字典的问题

原代码运行后输出空字典,核心问题出在文件指针提前耗尽、冗余循环调用以及未初始化的全局变量上,具体问题点如下:

  • 执行price_file = price_file2.readlines()时,已将文件所有内容读取到列表,同时文件对象price_file2的指针移动到了文件末尾。后续把price_file2传给addpricefile函数时,函数内的循环遍历不到任何内容。
  • 全局变量item_to_price未提前初始化,且没有有效赋值操作,自然保持空字典状态。
  • 外部的for next_line in price_file循环完全多余,重复调用函数也无法读取到任何内容。

修复方案1:最佳实践(无全局变量)

避免使用全局变量,直接在函数内初始化字典,正确传递读取的文件内容:

def addpricefile(lines):  
    # 输入:读取到的文件行列表
    # 输出:商品与价格的映射字典
    item_to_price = {}
    for next_line in lines: 
        item, price = next_line.strip().split(',')
        item_to_price[item] = float(price[1:])  # 去除$符号并转为浮点数
    return item_to_price    

p = input("Enter price file: ")
with open(p, "r") as price_file2:
    price_lines = price_file2.readlines()
    item_to_price = addpricefile(price_lines)
print(item_to_price)

注:使用with语句会自动关闭文件,无需手动调用close(),更安全可靠。

修复方案2:基于原代码修改(保留全局变量)

如果要保留原函数的全局变量逻辑,需移除冗余操作并初始化全局字典:

def addpricefile(price_file):  
    # 输入:价格文件对象
    # 输出:商品与价格的映射字典
    global item_to_price 
    item_to_price = {}  # 初始化全局字典
    for next_line in price_file: 
        item, price = next_line.strip().split(',')
        item_to_price[item] = float(price[1:])  # 去除$符号并转为浮点数
    return item_to_price    

p = input("Enter price file: ")
price_file2 = open(p, "r")
addpricefile(price_file2)  # 直接调用函数,无需额外循环
print(item_to_price)
price_file2.close()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 14:55:21