ankur suman
ankur suman

Reputation: 151

Convert CSV to Bytes-like Object in python

I have a dataframe and I'm changing that datafram to csv using

new_csv = df.to_csv()

Now i want to convert this new_csv into bytes object . When I try this:

new_bytes_obj = io.BytesIO(new_csv) 

I get an error :

TypeError: a bytes-like object is required, not 'str

Any way to do that?

Upvotes: 0

Views: 10420

Answers (1)

tripleee
tripleee

Reputation: 189477

It's not clear from your question why you want a BytesIO object. The natural and obvious and usually correct solution for textual data is to encapsulate it in a StringIO object instead.

new_str_obj = io.StringIO(new_csv)

If you need BytesIO, your str data needs to be converted to bytes data instead. In this case, you need to decide how to encode your string; if you don't know, UTF-8 is often a good guess, but you probably should spend some time on understanding what this actually means for your specific application.

new_bytes_obj = io.BytesIO(new_csv.encode('utf-8'))

Probably read http://nedbatchelder.com/text/unipain.html and/or Joel Spolsky's The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!) now rather than later.

Upvotes: 1

Related Questions