將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