yodish
yodish

Reputation: 763

Printing Pandas dataframe to a text file and adding lines, why is \n adding a space?

I'm printing a dataframe to a text file and want to add a couple lines, at the top.

import pandas as pd

df = pd.DataFrame(data={'Title': ['Movie1', 'Movie2', 'Movie3', 'Movie4'],
                        'Date': ['2010', '2020', '2009', '2019'],
                        'Names': ['Bob,Jim', 'Jim,Harry,Lou', 'Scott', 'Bill,Jim']})

some_string = "This is my list"
another_string = "It's Fun!"

print(some_string,"\n",another_string,"\n",df, file=open(r'C:path\to\file.txt', 'w' ))

Current output is this:

This is my list 
 It's Fun! 
     Title  Date          Names
0  Movie1  2010        Bob,Jim
1  Movie2  2020  Jim,Harry,Lou
2  Movie3  2009          Scott
3  Movie4  2019       Bill,Jim

I'm sure these are simple fixes, but:

1) How do I eliminate the 1-character shift to the right that is occuring when I use \n?

2) How do I remove the index column? I've tried adding index=False in several places but can't seem to figure it out this morning. I'd prefer to remove the index during the write (rather than the read).

Upvotes: 1

Views: 483

Answers (1)

jezrael
jezrael

Reputation: 862451

One idea is join all strings together with + and for DataFrame use DataFrame.to_string method with index=False:

print(some_variable + "\n" + another_variable + "\n" + df.to_string(index=False))
This is my list
It's Fun!
  Title  Date          Names
 Movie1  2010        Bob,Jim
 Movie2  2020  Jim,Harry,Lou
 Movie3  2009          Scott
 Movie4  2019       Bill,Jim

Another idea from comment - paramter sep='\', thanks @Chris A:

print(some_variable, another_variable, df.to_string(index=False), sep='\n')

Upvotes: 2

Related Questions