Home > front end >  Saving dataframe after text lines in .txt file
Saving dataframe after text lines in .txt file

Time:04-27

I am trying to modify a raw data .txt file to be reprocessed by a software. Problem is, that software needs additional parameters that are in the text file before the data table. As such, df.to_csv overwrites the lines which I need.

The string approach was successful but would not let me use '\t' separators

#Building example dataframe
index = [0,1,2,3,4,5]
t = pd.Series([2,6,9,8,10,12],index= index)
s = pd.Series([7,2,6,8,5,9],index= index)
df = pd.DataFrame({'Time (s)':t,'X Position':x})


file="C:/Users/user/Desktop/example.txt"

f = open(file, "w") 
f.write(f"Multiple\nlines\ngo here\n\n")
f.close()

with open(file, 'a') as f:
    dfAsString = df.to_string(index=False)
    f.write(dfAsString)
    f.close()

This gives the following .txt output:

Multiple
lines
go here

 Time (s)  X Position
        2           7
        6           2
        9           6
        8           8
       10           5
       12           9

I need to add this dataframe to the file but also need the output to be tab separated without affecting the text above. Help is very welcome.

CodePudding user response:

In addition to a file path, DataFrame.to_csv() can take an already-opened file:

file="C:/Users/user/Desktop/example.txt"
with open(file, 'w') as f:
    f.write(f"Multiple\nlines\ngo here\n\n")
    df.to_csv(f, sep='\t', index=False)

Output in example.txt:

Multiple
lines
go here

Time (s)    X Position
2   7
6   2
9   6
8   8
10  5
12  9

CodePudding user response:

You can use to_csv to append new dataframe (tab separated) to an existing file:

file="example.txt" 
f = open(file, "w") 
f.write(f"Multiple\nlines\ngo here\n\n")
f.close()
df.to_csv(file, mode='a', index=False, header=True, sep = "\t")

The output of this is:

Multiple
lines
go here

Time (s)    X Position
2   7
6   2
9   6
8   8
10  5
12  9
  • Related