[英]Convert .xlsx to .txt with python? or format .txt file to fix columns indentation?
I have an excel file with many rows/columns and when I convert the file directly from .xlsx to .txt with excel, the file ends up with a weird indentation (the columns are not perfectly aligned like in an excel file) and due to some requirements, I really need them to be.我有一个包含许多行/列的 excel 文件,当我使用 excel 将文件直接从 .xlsx 转换为 .txt 时,该文件最终会出现奇怪的缩进(列不像在 excel 文件中那样完全对齐)并且由于一些要求,我真的需要它们。
So, is there a better way to write from excel to txt using python?那么,有没有更好的方法使用python从excel写入txt? or format the txt file so the columns perfectly align?或格式化 txt 文件,使列完美对齐?
I found this code in a previous question but I am getting the following error:我在上一个问题中找到了此代码,但出现以下错误:
TypeError: a bytes-like object is required, not 'str'
Code:代码:
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))
is there a better way to write from excel to txt using python?有没有更好的方法使用python从excel写入txt?
I'm not sure if it's a better way, but you could write the contents of xlsx
file to txt
this way:我不确定这是否是更好的方法,但是您可以通过这种方式将xlsx
文件的内容写入txt
:
import pandas as pd
with open('test.txt', 'w') as file:
pd.read_excel('test.xlsx').to_string(file, index=False)
Edit:编辑:
to convert date
column to a desired format, you could try the following:要将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='')
The problem lies in this row:问题出在这一行:
with open('my.csv', 'wb') as myCsvfile:
' wb
' suggests you will be writing bytes, but in reality, you will be writing regular characters. ' wb
' 表明您将写入字节,但实际上,您将写入常规字符。 Change it to ' w
'.将其更改为“ w
”。 Perhaps the best practice would be to also use with block for Excel file:也许最好的做法是对 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.