Python CSV文件读取、清洗及写入

图片名称

  近期项目总遇到csv格式文件,遂记录一下该文件的读取、清洗及写入方式,供大家参考:
  原始数据下载地址:test_new.csv
  Python实现代码如下:

import csv

infile = "d:\\test_csv.csv"
outfile = "d:\\test_new.csv"

datas = []
with open(infile, "r") as f:
    reader = csv.reader(f)
    header = next(reader) # 跳过表头
    for row in reader:
        row = [_.replace(",", ",") for _ in row] # 替换文本中的关键字
        if row[3] and row[4]: # 字段不为空
            datas.append(",".join(row[0:-1]).replace("\n", ""))

print("\n".join(datas), file=open(outfile, "w", encoding="gbk"))

分类: Python技术