CSV文件交互中的日期校验与任务统计实现方案
CSV任务数据处理Python代码
核心函数说明
- check_day:校验指定日期是否存在于
data.csv文件中 - range_day:定位指定日期对应的任务行的起止索引
- count_task_values:统计指定日期下的任务信息,若任务名称为空但有任务内容,会自动合并到上一条任务中
import csv def check_day(date_to_check): file_path = "data.csv" try: with open(file_path, mode='r', newline='', encoding='utf-8-sig') as file: reader = csv.reader(file) next(reader) # 跳过表头 for row in reader: if row[0].strip() == str(date_to_check): print(f"你查询的日期 {date_to_check} 存在。") return True print(f"日期 {date_to_check} 不存在于CSV文件中。") return False except Exception as e: print("读取CSV文件时出错:", e) return False def range_day(date_to_check): file_path = "data.csv" start_index, end_index = None, None try: with open(file_path, mode='r', newline='', encoding='utf-8-sig') as file: reader = csv.reader(file) next(reader) # 跳过表头 for index, row in enumerate(reader): if row[0].strip() == str(date_to_check): start_index = index elif start_index is not None and row[0].strip() != "" and row[0].strip() != str(date_to_check): end_index = index - 1 break if end_index is None: end_index = index # 如果未找到新日期,结束于最后一行 if start_index is not None and end_index is not None: # 跳过表头行索引,转换为实际文件行号 start_index += 1 end_index += 1 return start_index, end_index else: print(f"日期 {date_to_check} 未在CSV文件中找到。") return None, None except Exception as e: print("读取CSV文件时出错:", e) return None, None def count_task_values(input_date): start_index, end_index = range_day(input_date) if start_index is None or end_index is None: print("无法统计任务,因为日期未在CSV文件中找到。") return None task_values = [] # 存储该日期对应的任务信息列表 try: file_path = "data.csv" with open(file_path, mode='r', newline='', encoding='utf-8-sig') as file: reader = csv.reader(file) next(reader) # 跳过表头 for index, row in enumerate(reader, start=1): if index < start_index or index > end_index: continue if row[1].strip() and row[2].strip(): task_values.append((row[1], row[2])) # 将任务信息存入列表 elif not row[1].strip() and row[2].strip() and task_values: # 若任务名称为空但有任务内容,且已有任务存储,则合并到上一条任务 last_task = task_values[-1] task_values[-1] = (last_task[0], last_task[1] + ', ' + row[2]) # 合并新旧任务内容 if task_values: print(f"日期 {input_date} 共有 {len(task_values)} 项任务:") for task_value in task_values: print(f"任务 1 -- CAM : {task_value[0]} -- MC : {task_value[1]}") else: print(f"日期 {input_date} 没有任务。") return task_values except Exception as e: print("读取CSV文件时出错:", e) return None # 调用函数示例:检查CSV文件中的日期并统计任务 input_date = int(input("请输入要查询的日期: ")) if check_day(input_date): range_day(input_date) count_task_values(input_date)
内容的提问来源于stack exchange,提问作者daocanon
相关产品推荐
相关产品推荐

