繁体   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