How to export a column from a dataframe to a text file with left alignment in Python Pandas?
Asked Answered
S

1

6

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.

Sensitivity answered 19/2, 2022 at 11:2 Comment(2)
You only have one column, so just use df.to_csv("output.txt", index=False, header=False) instead?Sepalous
shxt! how can this be so easy? I totally didn't not to_csv can be used to save as txt file. Thank you @SepalousSensitivity
L
6

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
Leacock answered 19/2, 2022 at 11:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.