Python 将txt转成csv文件

图片名称

  最近在跟进项目的时候,遇到了一个数据清洗的需求,该需求要求按照双引号成行,以竖线分隔,将txt文件转换成csv文件。
  原始数据下载地址:1.txt
  Python实现代码如下:

fpath = "d:\\1.txt"
with open(fpath, "r", encoding="utf-8") as f:
    datas = [_.replace("\n","") for _ in f.readlines()]

datas = "".join(datas).split("\"\"")
print(len(datas))

tmp = []
for i, data in enumerate(datas):
    data = data.replace("\"","").split("|")
    data_num = len(data)
    if data_num >= 3:
        tmp.append(",".join(["",data[0],"","",data[1],data[2],""]))
    else:
        print("line:{0}, context:{1}".format(i + 1,data))

datas = ["序号, id号, 时间, 电话, 标题, 摘要, 反馈内容"] + tmp
print("\n".join(datas), file=open("d:\\1.csv","w",encoding="gbk"))

分类: Python技术