简体   繁体   中英

Odd behavior with pandas and to_csv

I ran into an interesting thing today with using pandas to_csv() that I'm not sure is intended behavior. I thought I'd put it up here and see if anyone had any thoughts.

I had a data set with some text in it and some utf-8 encoded characters.

import pandas as pd
df = pd.read_csv('file',encoding='utf-8)
#Do some work
with open('file','w') as f:
    pd.to_csv(f , encoding ='utf-8')

This would throw an ascii encoding error that made me feel like an idiot If I switched to this pattern :

file_out = 'file.csv'
pd.to_csv(file_out,encoding = 'utf-8')

Worked just fine.

Any ideas if this is intended behavior ?

You're missing the closing quote.

import pandas as pd
df = pd.read_csv('file.csv', encoding='utf-8')

with open('file.csv', 'w') as f:
    pd.to_csv(f, encoding='utf-8')  

Additionally, you should not add spaces between the parameters and passed values. Also, add the file ending to the file you are passing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM