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.

2
  • 2
    You only have one column, so just use df.to_csv("output.txt", index=False, header=False) instead? Commented Feb 19, 2022 at 12:55
  • 1
    shxt! how can this be so easy? I totally didn't not to_csv can be used to save as txt file. Thank you @Timus Commented Feb 20, 2022 at 14:20

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.