簡體   English   中英

使用 python 將 .xlsx 轉換為 .txt? 或格式化 .txt 文件以修復列縮進?

[英]Convert .xlsx to .txt with python? or format .txt file to fix columns indentation?

我有一個包含許多行/列的 excel 文件,當我使用 excel 將文件直接從 .xlsx 轉換為 .txt 時,該文件最終會出現奇怪的縮進(列不像在 excel 文件中那樣完全對齊)並且由於一些要求,我真的需要它們。

那么,有沒有更好的方法使用python從excel寫入txt? 或格式化 txt 文件,使列完美對齊?

我在上一個問題中找到了此代碼,但出現以下錯誤:

TypeError: a bytes-like object is required, not 'str'

代碼:

import xlrd
import csv

# open the output csv
with open('my.csv', 'wb') as myCsvfile:
    # define a writer
    wr = csv.writer(myCsvfile, delimiter="\t")

    # open the xlsx file 
    myfile = xlrd.open_workbook('myfile.xlsx')
    # get a sheet
    mysheet = myfile.sheet_by_index(0)

    # write the rows
    for rownum in range(mysheet.nrows):
        wr.writerow(mysheet.row_values(rownum))

有沒有更好的方法使用python從excel寫入txt?

我不確定這是否是更好的方法,但是您可以通過這種方式將xlsx文件的內容寫入txt

import pandas as pd

with open('test.txt', 'w') as file:
    pd.read_excel('test.xlsx').to_string(file, index=False)

編輯:

要將date列轉換為所需的格式,您可以嘗試以下操作:

with open('test.txt', 'w') as file:
    df = pd.read_excel('test.xlsx')
    df['date'] = pd.to_datetime(df['date']).dt.strftime('%Y%m%d')
    df.to_string(file, index=False, na_rep='')

問題出在這一行:

with open('my.csv', 'wb') as myCsvfile:

' wb ' 表明您將寫入字節,但實際上,您將寫入常規字符。 將其更改為“ w ”。 也許最好的做法是對 Excel 文件也使用 with 塊:

import xlrd
import csv

# open the output csv
with open('my.csv', 'w') as myCsvfile:
    # define a writer
    wr = csv.writer(myCsvfile, delimiter="\t")

    # open the xlsx file 
    with xlrd.open_workbook('myfile.xlsx') as myXlsxfile:
        # get a sheet
        mysheet = myXlsxfile.sheet_by_index(0)
        # write the rows
        for rownum in range(mysheet.nrows):
            wr.writerow(mysheet.row_values(rownum))
import pandas as pd

read_file = pd.read_excel (r'your excel file name.xlsx', sheet_name='your sheet name')
read_file.to_csv (r'Path to store the txt file\File name.txt', index = None, header=True)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM