python转换数据格式_python实现一组典型数据格式转换

本文实例为大家分享了一组典型数据格式转换的python实现代码,供大家参考,具体内容如下

有一组源数据,第一行会是个日期数据,第二行标明字段,再接下来是两行数据行。1018 14:31:30.193

Type Succ Fail

sour_sm 1308 1205

data_sm 2205 3301

1019 16:32:30.201

Type Succ Fail

data_sm 3308 2206

data_sm 1765 1105

1020 18:00:00.203

Type Succ Fail

sour_sm 7804 1105

data_sm 2976 1300

要转换成数据Time               Type    Succ Fail  Total

1018 14:31:30.193  sour_sm 1308 1205  2513

1018 14:31:30.193  data_sm 2205 3301  5506

1019 16:32:30.201  data_sm 3308 2206  5514

1019 16:32:30.201  data_sm 1765 1105  2870

1020 18:00:00.203  sour_sm 7804 1105  8909

1020 18:00:00.203  data_sm 2976 1300  4276

这个时候可以使用Python来处理,代码如下:

# coding = utf-8

fd = open(r"output.txt", "w", encoding="utf-8")

fd.write("%stttt%st%st%st%sn" % ("Time", "Type", "Succ", "Fail", "Total"))

with open(r"data.txt", "r", encoding="utf-8") as fd1:

lines = fd1.readlines()

time1 = lines[0::4] data1 = lines[2::4] data2 = lines[3::4] for (i, line) in enumerate(time1):

Time = line.strip()

Type_1 = data1[i].strip().split()[0] Succ_1 = data1[i].strip().split()[1] Fail_1 = data1[i].strip().split()[2] Total_1 = str(int(Succ_1) + int(Fail_1))

Type_2 = data2[i].strip().split()[0] Succ_2 = data2[i].strip().split()[1] Fail_2 = data2[i].strip().split()[2] Total_2 = str(int(Succ_2) + int(Fail_2))

fd.write("%st%st%st%st%sn" % (Time, Type_1, Succ_1, Fail_1, Total_1))

fd.write("%st%st%st%st%sn" % (Time, Type_2, Succ_2, Fail_2, Total_2))

fd.close()

生成文件格式如下,基本上满足了需求。

cee3c8cbe556d4bd1a35881a74c0c48e.png

您可能感兴趣的文章:把JSON数据格式转换为Python的类对象方法详解(两种方法)python3 json数据格式的转换(dumps/loads的使用、dict to str/str to dict、json字符串/字典的相互转换)在Python的struct模块中进行数据格式转换的方法基于YUV 数据格式详解及python实现方式

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值