以下是一个示例代码,它通过读取文件中的产品信息,按价格对产品进行排序并将结果写回到文件中:
# 读取文件中的产品信息
with open('products.txt', 'r') as file:
products = file.readlines()
# 将产品信息转换为列表
product_list = []
for product in products:
name, price = product.strip().split(',')
product_list.append((name, float(price)))
# 按价格对产品进行排序
sorted_products = sorted(product_list, key=lambda x: x[1])
# 将排序结果写回到文件中
with open('sorted_products.txt', 'w') as file:
for product in sorted_products:
file.write(f'{product[0]},{product[1]}\n')
假设文件中的产品信息格式为每行一个产品,以逗号分隔产品名称和价格,例如:
产品A,10.5
产品B,20.3
产品C,15.2
运行以上代码后,会生成一个新的文件sorted_products.txt
,内容为按价格排序后的产品信息。
下一篇:按价格过滤产品(从……到……)