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).
One idea is join all strings together with
+
and forDataFrame
useDataFrame.to_string
method withindex=False
:Another idea from comment - paramter
sep='\'
, thanks @Chris A: