Pandas: use to_csv with tempfile

Created on 13 Apr 2012  路  4Comments  路  Source: pandas-dev/pandas

I'd like to be able to write csv to temporary files and not have to worry about cleaning them up after they are sent to a user. Is it possible to have an optional file parameter on the to_csv methods, which would be used instead of the string filename? This could then be any file-like object (or even any suitable io object?)

Enhancement IO Data

Most helpful comment

What's wrong with

with tempfile.NamedTemporaryFile as temp:
    df.to_csv(temp.name, ...)

or something similar?

All 4 comments

What's wrong with

with tempfile.NamedTemporaryFile as temp:
    df.to_csv(temp.name, ...)

or something similar?

Thanks - I really should have thought of that. I've been using the csv module too much...

Ben

On 13 Apr 2012, at 21:14, Kamil Kisiel wrote:

What's wrong with

with tempfile.NamedTemporaryFile as temp:
df.to_csv(temp.name, ...)

or something similar?


Reply to this email directly or view it on GitHub:
https://github.com/pydata/pandas/issues/1047#issuecomment-5124117

You can use a string or any file-like object.

In [80]: df
Out[80]:
   A  B  C
a  3  2  3
b  3  2  2
c  3  3  2

In [81]: buffer = StringIO.StringIO()

In [82]: df.to_csv(buffer)

In [83]: print buffer.getvalue()
,A,B,C
a,3,2,3
b,3,2,2
c,3,3,2


In [84]: f = tempfile.NamedTemporaryFile()

In [85]: df.to_csv(f)

It also works for a Series (although undocumented).

In [86]: df['A'].to_csv(f)

In [87]: df['A'].to_csv(buffer)

with tempfile.NamedTemporaryFile(mode='r+') as temp:
we need to change the mode then only df will export the data into tempfile

Was this page helpful?
0 / 5 - 0 ratings