将txt格式转化为excel

一、需求解释

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

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

 

 

二、思路

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

 

三、代码展示

3.1 方法一

import pandas as pd
import openpyxl


file = r'D:\测试\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(r'D:\测试\nicai\result.xlsx', index=False)

 

3.1 方法二

import pandas as pd
import openpyxl


file = r'D:\测试\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(r'D:\测试\nicai\result.xlsx', index=False)

 

posted @ 2020-06-02 09:52  qsl_你猜  阅读(1149)  评论(0编辑  收藏  举报