使用python zipfile模块我创建了一个zip文件,如下所示:
CREATE TABLE #myTable (
Name VARCHAR(50),
Year INT,
Hours INT
)
INSERT INTO #myTable *.... some values*
DECLARE @var INT
SET @var = 2015
DECLARE @DynamicPivot NVARCHAR(MAX)
SET @DynamicPivot = '
SELECT *
FROM #myTable
PIVOT(
SUM(Hours) FOR Year IN ([' + CAST(@var as nvarchar(10)) + '])
) AS PvtTable'
EXEC sp_executesql @DynamicPivot
DROP TABLE #myTable
现在,我希望将此s = StringIO()
zip_file = zipfile.ZipFile(s, "w")
zip_file.write('/local/my_files/my_file.txt')
s.seek(0)
保存在我的文件系统中,路径zip_file
为/local/my_files/
。
一般来说,为了保存noraml文件,我使用了以下流程:
my_file.zip
但是,我认为我无法用这个来保存zipfile。任何人都可以帮我完成这件事。
答案 0 :(得分:3)
zip_file = zipfile.ZipFile("/local/my_files/my_file.zip", "w")
zip_file.write('/local/my_files/my_file.txt')
zip_file.close()
ZipFile
对象初始化的第一个参数是您要保存zip文件的路径。
答案 1 :(得分:0)
如果您需要使用StringIO,请尝试以下代码:
from StringIO import StringIO
import zipfile
s = StringIO()
with zipfile.ZipFile(s, "w", compression=zipfile.ZIP_DEFLATED) as zf:
zf.write('/local/my_files/my_file.txt')
with open('/local/my_files/my_file.zip', 'wb') as f_out:
f_out.write(s.getvalue())
或者你可以用更简单的方式做到:
import zipfile
with zipfile.ZipFile("/local/my_files/my_file.zip", "w", compression=zipfile.ZIP_DEFLATED) as zf:
zf.write("/local/my_files/my_file.txt")