首页 > 其他 > 详细

将txt格式转化为excel

时间:2020-06-02 10:50:45      阅读:33      评论:0      收藏:0      [点我收藏+]

一、需求解释

txt格式是由json格式进行保存的。

需要将txt格式转化为excel格式。

技术分享图片

 

 

二、思路

  • 将txt分行读取
  • 将读取的内容转化为字典
  • 将字典格式转化为DataFrame格式
  • 循环执行上述操作,直至全部读完内容
  • 保存为excel格式

 

三、代码展示

3.1 方法一

import pandas as pd
import openpyxl


file = rD:\测试\nicai\result.txt
i = 0
with open(file, r,encoding= utf-8) as file_object:
    for line in file_object:
        line = eval(line)
        index = line[id]
        if i == 0:
            df = pd.DataFrame(line, index= [index])
            i = 1
        else:
            df_x = pd.DataFrame(line, index=[index])
            df = df.append(df_x)


df.to_excel(rD:\测试\nicai\result.xlsx, index=False)

 

3.1 方法二

import pandas as pd
import openpyxl


file = rD:\测试\nicai\result.txt
with open(file, r,encoding= utf-8) as file_object:
    for i, line in enumerate(file_object):
        line = eval(line)
        if i == 0:
            df = pd.DataFrame(line, index= [i])
        else:
            df_x = pd.DataFrame(line, index=[i])
            df = df.append(df_x)

df.to_excel(rD:\测试\nicai\result.xlsx, index=False)

 

将txt格式转化为excel

原文:https://www.cnblogs.com/qianslup/p/12979079.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!