使用 python? 将.xlsx转换为.txt,或格式化.txt文件以修复列缩进



我有一个包含许多行/列的 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 文件使用块:

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 fileFile name.txt', index = None, header=True)

最新更新