Pandas: `df.to_csv` on python3 throws `TypeError: a bytes-like object is required, not 'str'`

Created on 11 Jan 2016  Â·  5Comments  Â·  Source: pandas-dev/pandas

The following code throws that error:

In [1]: import pandas as pd
In [2]: import numpy as np
In [3]: df = pd.DataFrame(np.random.randn(10, 5), columns=['a', 'b', 'c', 'd', 'e'])
In [4]: import tempfile
In [5]: tf = tempfile.NamedTemporaryFile()
In [6]: df.to_csv(tf)

Am I missing something?

Most helpful comment

You'll want tf = tempfile.NamedTemporaryFile(mode='w') or wt since you're writing text, not bytes. Check if that works for you?

All 5 comments

You'll want tf = tempfile.NamedTemporaryFile(mode='w') or wt since you're writing text, not bytes. Check if that works for you?

It does. Thanks!

On Mon, Jan 11, 2016 at 2:41 PM, Tom Augspurger [email protected]
wrote:

You'll want tf = tempfile.NamedTemporaryFile(mode='w') or wt since you're
writing text, not bytes. Check if that works for you?

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

df.to_csv(tf)
how to read after this line?? i need to read tf, also need to mail the csv file

how to check whether df.to_csv(tf) is properly exported as csv, df has data , tf has data may be not how to read and print tf?

@balaprasad18 You might try searching on stackoverflow under the pandas tag.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

amelio-vazquez-reina picture amelio-vazquez-reina  Â·  3Comments

nathanielatom picture nathanielatom  Â·  3Comments

matthiasroder picture matthiasroder  Â·  3Comments

swails picture swails  Â·  3Comments

idanivanov picture idanivanov  Â·  3Comments