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

Python实现CSV文件工时按客户汇总并导出需求求助

实现客户工时汇总并导出CSV的解决方案

嘿,你已经搞定了读取CSV的第一步,很棒!接下来咱们一步步完成汇总和导出的功能,其实没那么复杂~

步骤1:汇总各客户的总工时

首先,咱们需要一个字典来记录每个客户的累计工时——客户名称作为唯一的键,对应的值就是总工时。注意CSV里的“工时”字段是字符串类型,得先转换成数字(整数或浮点数)才能累加。

这里先给你最基础、容易理解的版本:

import csv

# 读取CSV数据到列表(你的原有代码)
results = []
with open('Time_export.csv', encoding='utf-8') as File:
    reader = csv.DictReader(File)
    for row in reader:
        results.append(row)

# 初始化字典存储客户总工时
customer_hours = {}

# 遍历每一行数据,累加工时
for row in results:
    customer_name = row['客户']
    # 把工时字符串转成浮点数(如果是整数用int()也可以)
    work_hours = float(row['工时'])
    
    # 如果客户已经在字典里,就累加;否则初始化
    if customer_name in customer_hours:
        customer_hours[customer_name] += work_hours
    else:
        customer_hours[customer_name] = work_hours

# 打印汇总结果验证一下(比如Apple应该是11,Nokia是5)
print(customer_hours)

如果想让代码更简洁,可以用collections模块里的defaultdict,省去判断客户是否存在的步骤:

from collections import defaultdict

# 替换上面的字典初始化和遍历部分
customer_hours = defaultdict(float)
for row in results:
    customer_name = row['客户']
    work_hours = float(row['工时'])
    customer_hours[customer_name] += work_hours

步骤2:把汇总结果导出为新CSV

接下来咱们把汇总好的数据写入新的CSV文件,需要定义表头(比如['客户', '总工时']),然后把字典里的键值对逐行写入:

# 导出汇总数据到新CSV
with open('Customer_Hours_Summary.csv', 'w', newline='', encoding='utf-8') as output_file:
    # 定义表头
    fieldnames = ['客户', '总工时']
    writer = csv.DictWriter(output_file, fieldnames=fieldnames)
    
    # 写入表头
    writer.writeheader()
    
    # 遍历字典,写入每一行数据
    for customer, total_hours in customer_hours.items():
        writer.writerow({'客户': customer, '总工时': total_hours})

print("汇总CSV已成功导出!")

完整整合代码

把上面的步骤整合起来,就是完整的可运行脚本啦:

import csv
# 如果用defaultdict的话就加上下面这行
# from collections import defaultdict

def main():
    # 读取原始CSV
    results = []
    with open('Time_export.csv', encoding='utf-8') as input_file:
        reader = csv.DictReader(input_file)
        for row in reader:
            results.append(row)
    
    # 汇总工时
    customer_hours = {}
    # 用defaultdict的话替换成:customer_hours = defaultdict(float)
    for row in results:
        customer = row['客户']
        hours = float(row['工时'])
        if customer in customer_hours:
            customer_hours[customer] += hours
        else:
            customer_hours[customer] = hours
    
    # 导出汇总CSV
    with open('Customer_Hours_Summary.csv', 'w', newline='', encoding='utf-8') as output_file:
        fieldnames = ['客户', '总工时']
        writer = csv.DictWriter(output_file, fieldnames=fieldnames)
        writer.writeheader()
        for customer, total in customer_hours.items():
            writer.writerow({'客户': customer, '总工时': total})
    
    print("汇总完成,结果已保存到Customer_Hours_Summary.csv")

if __name__ == "__main__":
    main()

小提示

  • 确保你的CSV文件里的字段名和代码里的row['客户']、row['工时']完全一致(比如不要有空格或者大小写差异)
  • 如果工时是整数,把float()改成int()就可以啦
  • 运行脚本前,确保Time_export.csv和脚本在同一个文件夹里,或者写完整的文件路径

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 23:27:54