pythondataframetxt

Write a dataframe in txt on left margin


I want to create a dataframe like this:

df_finale = pd.DataFrame({'col0': '#define ', 'col1': var, 'col2': ' ', 'col3': var1})

where var is a dataframe of string and var1 is a dataframe made with numbers and then write it into a txt using python.

with open('C:\python\tests.txt', 'a') as f:
    df_string = df_finale.to_string(header=False, index=False)
    f.write(df_string)

but I see that in the txt the indentation is wrong. I'd like to have all the lines that begins on the left margin


Solution

  • in the end I've found this solution

    df=tabulate(df, showindex=False, headers=df.columns)
    

    it worked for me, removing the index and maintaining a correct indentation on the left.

    This solution was proposed here:

    How to set the pandas dataframe data left/right alignment?