如何将CSV中已使用行移至新文件并删除原行?
CSV已使用数据行迁移与清理实现
需求说明
原本仅跳过CSV中的已使用数据行,现需将这些已使用行迁移至单独的used.csv文件,原CSV仅保留未使用数据,且可重复执行该操作。
实现代码
import csv import os def process_used_rows(path_to_csv, used_csv_path="used.csv"): # 1. 读取原CSV所有数据 with open(path_to_csv, 'r', newline='', encoding='utf-8') as f: reader = csv.reader(f) all_rows = list(reader) if not all_rows: print("原CSV文件已无数据") return # 2. 打印待迁移的已使用数据行 print("待迁移的已使用数据行:") for row in all_rows: print(row) # 3. 将数据追加至used.csv(文件不存在则自动创建) file_exists = os.path.isfile(used_csv_path) with open(used_csv_path, 'a', newline='', encoding='utf-8') as f: writer = csv.writer(f) # 首次创建文件时写入表头(若原CSV有表头) if not file_exists and all_rows: writer.writerow(all_rows[0]) # 写入所有已使用数据行(如需排除表头,可改为all_rows[1:]) writer.writerows(all_rows) # 4. 清理原文件中的已使用数据行 # 若需保留未使用数据,可提前拆分all_rows为已使用/未使用两组,仅写入未使用行 with open(path_to_csv, 'w', newline='', encoding='utf-8') as f: pass print("数据已迁移至used.csv,原文件已清理") # 示例调用 if __name__ == "__main__": path_to_csv_file = "your_data.csv" # 重复执行操作,可自定义退出条件 while True: process_used_rows(path_to_csv_file) user_input = input("是否继续执行?(y/n):") if user_input.lower() != 'y': break
代码说明
- 读取数据:一次性读取原CSV全部内容,便于后续批量处理
- 打印数据:直观输出待迁移的已使用行,确认操作对象
- 迁移至used.csv:采用追加模式写入,避免覆盖历史迁移数据;自动识别文件是否存在,首次创建时可同步写入表头
- 清理原文件:示例中直接清空原文件,若需保留未使用数据,可提前拆分数据组,仅写入未使用行到原文件
- 重复执行:通过循环实现重复操作,可根据需求调整退出逻辑
内容的提问来源于stack exchange,提问作者Pitt
相关产品推荐
相关产品推荐

