I have a xlsx file. The text format in it is normal, everything aligning to the left. Now I want to extract a string column from it and save it into a txt file. My codes are as below:
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()
Ok, i have successfully created a text file. But my problem is, everything in this file is aligning to the right with many empty spaces in the front of each text string. A sample is as below,
Michael Jordan
Scottie Pippen
Dirk
Curry
What I want is the normal txt file format like this:
Michael Jordan
Scottie Pippen
Dirk
Curry
Left alignment without any format.
Would anyone please help? I have already tried many other solutions like set_properties, set_styles, etc, and have read many posts like this How to left align a dataframe column in python?, but my problem is not solved.
CodePudding user response:
If your column you want to write is named COLUMN_NAME
, you can do:
with open("output.txt", "w") as f_out:
f_out.write("\n".join(df["COLUMN_NAME"]))
This creates output.txt
:
Michael Jordan
Scottie Pippen
Dirk