我有一个xlsx文件,其中的文本格式正常,所有内容都向左对齐。现在我想从中提取一个字符串列并将其保存到txt文件中。我的代码如下:
import pandas as pd
import numpy as np
df = pd.read_excel('excel_file.xlsx',
sheet_name ='tab1'
)
df = df.drop(['L1','L2','L3'], axis=1)
# so that only 1 string column is left
w = open("output.txt", "w")
w.write (df.to_string(index=False, header=False))
w.close()
好的,我已经成功创建了一个文本文件。但我的问题是,这个文件中的所有内容都向右对齐,并在每个文本字符串前面有许多空白。一个示例如下:
Michael Jordan
Scottie Pippen
Dirk
Curry
我希望得到像这样的普通文本文件格式:
Michael Jordan
Scottie Pippen
Dirk
Curry
没有任何格式的左对齐。
请问有谁可以帮忙吗? 我已经尝试了很多其他解决方案,例如set_properties、set_styles等,并阅读了许多像如何在Python中左对齐数据框列?这样的帖子,但我的问题没有得到解决。
df.to_csv("output.txt", index=False, header=False)
来输出,不需要指定列名和索引。 - Timus