A note when you're building a web server in Python and want to download Pandas DataFrame as a CSV file.
body = df.to_csv(index=False).encode('utf_8_sig')
headers = {
'Content-Type': 'text/csv',
'Content-Disposition': 'attachment; filename="data.csv"',
}
return web.Response(body=body, headers=headers)
This is an example of aiohttp Server, but I think it's the same for other frameworks.
--pandas.DataFrame.to_csv
will return the CSV string as it is if you do not specify the output destination
--If the CSV file is expected to be opened in Excel, encode it with ʻutf_8_sig(UTF-8 with BOM) so that the characters will not be garbled. --You can specify the file name at the time of download by adding the
Content-Disposition` header.
--Encoding is required when using Japanese file names
This is the point.
Recommended Posts