Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

write a Pandas dataframe to a .txt file

Tags:

python

pandas

My code writes a txt file with lots of data. I'm trying to print a pandas dataframe into that txt file as part of my code but can't use .write() as that only accepts strings.

How do I take a pandas dataframe, stored as DF1 for example, and print it in the file?

I've seen similar questions but those are aimed at creating a txt file solely for the dataframe, I would just like my dataframe to appear in a txt file

like image 437
Alejandro Rodriguez Avatar asked Jan 27 '23 14:01

Alejandro Rodriguez


2 Answers

use the to_string method, and then you can use write with the mode set to append ('a')

tfile = open('test.txt', 'a')
tfile.write(df.to_string())
tfile.close()

Sample Data

import pandas as pd
import numpy as np

df = pd.DataFrame({'id': np.arange(1,6,1),
                   'val': list('ABCDE')})

test.txt

This line of text was here before.

Code

tfile = open('test.txt', 'a')
tfile.write(df.to_string())
tfile.close()

Output: test.txt

This line of text was here before.
   id val
0   1   A
1   2   B
2   3   C
3   4   D
4   5   E
like image 91
ALollz Avatar answered Jan 31 '23 22:01

ALollz


Pandas DataFrames have to_string(), to_json() and to_csv() methods that may be helpful to you, see:

https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_string.html

https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_csv.html

https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_json.html

Example of writing a text file to a string. Use 'w' flag to write and 'a' to append to a file.

example_string = df1.to_string()
output_file = open('file.txt','a')
output_file.write(example_string)
output_file.close()

If you are only looking to put certain information in the text file, you can do that using either pandas or json methods to select it, etc. and see the docs links above as well.

Before OP commented about appending I originally wrote an example about json. json supports a dump() method to help write to a file. However, in most cases, its not the most ideal format to keep appending output to vs. csv or txt. In case its useful to anyone:

import json 

filename = 'file.json'

with open(filename, 'w') as file:
    json.dump(df1.to_json(), file)
like image 26
firxworx Avatar answered Jan 31 '23 22:01

firxworx