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

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM