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

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

将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)

 

相关文章:

  • 2021-12-28
  • 2021-04-09
  • 2021-11-29
  • 2021-12-05
  • 2021-08-14
  • 2021-11-24
  • 2021-11-30
猜你喜欢
  • 2022-02-15
  • 2022-02-01
  • 2022-12-23
  • 2021-12-15
  • 2021-11-09
  • 2021-05-24
  • 2022-12-23
相关资源
相似解决方案