1

i Want to Zip the CSV File in (Buffer) Using zipFile in Python

Below is My Code Which I Have Tried And Error Log Attached

I Dont want to use the compression in df.to_csv due to Version issue 
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.StringIO() df.to_csv(s_buf,index=False) s_buf.seek(0) s_buf.name = 'my_filename.csv' localfile= io.BytesIO() localzip = io.BytesIO() zf = zipfile.ZipFile(localzip, mode="w",compression=zipfile.ZIP_DEFLATED) zf.writestr(localfile, s_buf.read()) zf.close() with open("D:/my_zip.zip", "wb") as f: f.write(zf.getvalue()) 

Error I am Getting

Traceback (most recent call last): File "C:/Users/Window/PycharmProjects/dfZip/dfZiptest.py", line 25, in <module> zf.writestr(localfile, s_buf.read()) File "C:\Python\Python37\lib\zipfile.py", line 1758, in writestr date_time=time.localtime(time.time())[:6]) File "C:\Python\Python37\lib\zipfile.py", line 345, in __init__ null_byte = filename.find(chr(0)) AttributeError: '_io.BytesIO' object has no attribute 'find' 

2 Answers 2

1
zf = zipFile.ZipFile("localzip.zip", mode="w", compression=zipfile.ZIP_DEFLATED) zf.write(filename + '.cvs', s_buf.read()) zf.close 

What you are doing here is

1 - You initializa the path of the ZipFile

2 - You simply pass the name and then the file you want to be written to the archive. In your case you were passing io.BytesIO() as a name, which made no sense to Python, thus the error.

I would strongly advice you, to resolve any Version issues first, because while 'clever' solution may seem like a quick way out, they tend to rack up a terrible technical debt latter, which can and will be a nightmare to deal with.

Sign up to request clarification or add additional context in comments.

1 Comment

this Line wont Work as the FIle in Buffer if Use This gives Error FileNotFoundError: [WinError 2] The system cannot find the file specified: 'my_filename.cvs'
0

You are passing a io.BytesIO() object as the first argument to ZipFile.writestr() where it expects either an archive name or a ZipInfo object.

zf.writestr(localfile, s_buf.read()) 

zinfo_or_arcname is either the file name it will be given in the archive, or a ZipInfo instance.

source: Docs

4 Comments

I Tried Doing that Change By Giving a File Name Now its Giving Error While Writing the Zip File
You'd need to post the error for me to provide further assistance.
Traceback (most recent call last): File "C:/Users/sagar/PycharmProjects/dfZip/dfZiptest.py", line 16, in <module> f.write(zf.getvalue()) AttributeError: 'ZipFile' object has no attribute 'getvalue'
The error is pretty obvious - ZipFile instances do not have a getvalue method. I think you need to review the documentation.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.