python-3.x 编辑CSV文件[已关闭]

iecba09b  于 2023-01-06  发布在  Python
关注(0)|答案(1)|浏览(157)

昨天关门了。
Improve this question
编辑CSV文件:orders.txt文件包含有关订购项目(订单行)的数据。
文件的每一行包含三个逗号分隔的值:OrderID-订单号,ProductName-产品,Sales-金额。第一行包含列名,应忽略。
程序必须计算并显示每个订单的总金额。
请注意,订单可以包含一个或多个项目(行)-例如,订单31包含三个项目(行)。文件中的行按订单编号排序。
警告:该任务只能通过文件和字符串的学习操作来解决;不允许使用专用模块(即:程序不能包含import语句!).
建议:

  • 下载orders.txt文件,然后将其上传到Replit(文件)!
  • 可以使用split()方法拆分文件行。
  • 文件包含带有"Chocolate Cookies"项的行-这些行不需要进一步处理

Order.txt
订单ID、产品名称、销售
三十,啤酒,一千四百
30,干李子,105.00
31,苹果干,530.00
31,干梨,300.00
31,干李子,35.00
32,猜,270. 00
32,咖啡,920.00
33,巧克力饼干,276.00
34,巧克力饼干,184.00
35,巧克力,127.50
36岁,蛤蜊杂烩,1930.00
37,咖喱酱,680.00
38,咖啡,13800.00
39,巧克力,1275.00
40,绿茶,598.00
42,巧克力饼干混合物,92.00
42,法国人,220.00
42岁,波森莓酱,250.00
45,蟹肉,920.00
45,蛤蜊浓汤,482.50
46,马苏里拉,1740.00
46岁,意大利饺子,1950年
47,啤酒,4200.00
48,巧克力饼干,230.00
48,咖喱酱,1000.00
50,司康尼斯,200.00
51,蟹肉,552.00
51,橄榄油,533.75
51分,蛤蜊浓汤,289.50分
55,啤酒,1218.00
56,巧克力,127.50
58,长粒稻,280.00
58,橘子酱,3240.00
60,马苏里拉,1392.00
63,糖浆,500.00
63,咖喱酱,120.00
67,杏仁,200.00
69,干李子,52.50
70,咖喱酱,800.00
71,蟹肉,736.00
72,咖啡,230.00
73,蛤蜊浓汤,96.50
74,巧克力,510.00
75,巧克力,510.00
76,加拿大风味,660.00
77,波森莓酱,2250.00
78,水果鸡尾酒,1560.00
79,苹果干,1590.00
79,干梨,900.00

ffx8fchx

ffx8fchx1#

我考虑了一会儿是否应该回答这个问题。
我100%同意,它看起来像你没有投入太多,如果有的话,努力到这一点之前,问它在这里。
它看起来也很像家庭作业中的复制/粘贴问题。

尽管如此

我已经花时间为你标记了每一行代码,我相信你会至少花时间仔细检查这段代码并学习它的功能。这都是非常简单的东西。如果你需要任何解释,我很乐意进一步帮助你。

# Open the file
file = 'C:\\PATH\\TO\\FILE\\orders.txt'
with open(file, 'r') as f:
    # Read the contents of the file into a list of lines
    lines = f.readlines()

# Initialize a dictionary to store the sales totals for each OrderID
sales_totals = {}

# Iterate over the lines, skipping first line which is column names
for line in lines[1:]:
    # Skip over blank lines in the textfile
    if line == '\n':
        continue

    # Split the line into a list of values, we are telling it to split on each comma
    values = line.strip().split(',')

    # Get the OrderID and Sales values
    # index's start at 0. Since order_id is the first column, it's index 0
    order_id = values[0]

    # sales is in the third column, since it start's from 0, that's index 2
    # we are also converting this string into a float so that we can perform
    # math functions on it later
    sales = float(values[2])

    # Add the Sales value to the total for the OrderID
    if order_id in sales_totals:
        # This is not the first occurrence of this order_id
        # so you want to add to the current sales total for this id
        sales_totals[order_id] += sales
    else:
        # This is the first occurrence of this order_id
        sales_totals[order_id] = sales

# Print the sales totals for each OrderID
for order_id, total in sales_totals.items():
    print(f'Order {order_id}: {total}')

相关问题