如何基于换行分隔的TXT文件实现库存数据解析与实例化?
问题描述
我有一个.txt文件,其中每个值单独占一行,内容如下:
229 flowers 7 2.99 456 bows 3 19.99
我原本编写的代码是按逗号分隔解析这些数据的,代码如下:
inventory_dict = {} #open inventory inventory_data = open(INVENTORY_FILE,'r') #read for line in inventory_data: values = line.split(',') #split items using commas item_id = values[0] name = values[1] #<-- storing the info in separate variables quantity = int(values[2]) price = float(values[3]) inventory_item = inventory.Inventory(item_id,name,quantity,price)#create an instance inventory_dict[item_id] = inventory_item
现在我需要修改代码,适配每个值单独占一行的格式,尝试用\n作为分隔符但未成功,请问该如何实现?
解决方案
你之前的思路问题在于:逐行读取时每一行只有单个值,用split(',')或者split('\n')都没法直接得到一组4个值。现在每4行对应一个完整的库存条目,必须批量读取4行作为一组来处理,以下是两种可行的修改方式:
方式一:迭代器逐组读取
利用文件对象的迭代器特性,每次读取4行组成一个条目:
inventory_dict = {} # 使用with语句自动管理文件关闭,避免资源泄漏 with open(INVENTORY_FILE, 'r') as inventory_data: lines_iter = iter(inventory_data) while True: try: # 逐行读取并去除换行符、空白字符 item_id = next(lines_iter).strip() name = next(lines_iter).strip() quantity = int(next(lines_iter).strip()) price = float(next(lines_iter).strip()) inventory_item = inventory.Inventory(item_id, name, quantity, price) inventory_dict[item_id] = inventory_item except StopIteration: # 读取到文件末尾时退出循环 break
方式二:一次性读入后分组处理
先把所有有效行读入列表,再按每4个元素一组遍历:
inventory_dict = {} with open(INVENTORY_FILE, 'r') as inventory_data: # 读取所有行,过滤空行并去除多余空白 all_lines = [line.strip() for line in inventory_data if line.strip()] # 按步长4遍历列表,每4个元素对应一个库存条目 for idx in range(0, len(all_lines), 4): item_id = all_lines[idx] name = all_lines[idx+1] quantity = int(all_lines[idx+2]) price = float(all_lines[idx+3]) inventory_item = inventory.Inventory(item_id, name, quantity, price) inventory_dict[item_id] = inventory_item
关键注意点
- 两种方式都用
with语句操作文件,比直接open更安全,能自动完成文件关闭。 - 必须用
strip()处理每行内容,否则会保留行尾的换行符\n,导致类型转换报错。 - 原代码的逐行拆分逻辑不再适用,因为单个行仅对应一个字段,必须4行凑齐一个完整的库存对象参数。
内容的提问来源于stack exchange,提问作者Lily
相关产品推荐
相关产品推荐

