I want to store the output of df
to csv
in Memory Object of BytesIo()
(Not StringIO
) and then zip it and here is my attempt:
import pandas as pd
import numpy as np
import io
import zipfile
df = pd.DataFrame(np.random.randn(100, 4), columns=list('ABCD'))
s_buf = io.BytesIO()
df.to_csv(s_buf)
s_buf.seek(0)
localfile= io.BytesIO()
zf = zipfile.ZipFile(localfile, mode="w",compression=zipfile.ZIP_DEFLATED)
zf.writestr(localfile, s_buf.read())
zf.close()
with open("D:/my_zip.zip", "wb") as f: # use `wb` mode
f.write(zf.getvalue())
By using pandas. DataFrame. to_csv() method you can write/save/export a pandas DataFrame to CSV File. By default to_csv() method export DataFrame to a CSV file with comma delimiter and row index as the first column.
Pandas is a very powerful and popular framework for data analysis and manipulation. One of the most striking features of Pandas is its ability to read and write various types of files including CSV and Excel.
The concept is the same, a table with functions to create or read files, this time XML/CSV files instead of Excel files. Just like with the Excel Buffer table, the XML buffer and CSV buffer table should be used as temporary tables.
Pandas DataFrame to_csv() function converts DataFrame into CSV data. We can pass a file object to write the CSV data into a file. Otherwise, the CSV data is returned in the string format.
I think this would be helpful:-
import gzip
from io import BytesIO
import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.randn(100, 4), columns=list('ABCD'))
b_buf = BytesIO()
with gzip.open(b_buf, 'wb') as f:
f.write(df.to_csv().encode())
b_buf.seek(0)
with open("my_zip.zip", "wb") as f:
f.write(b_buf.getvalue())
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With