zipfile将.zip输出写入.py文件位置

时间:2018-11-05 16:20:02

标签: python zipfile

以下脚本正在将zip写入.py文件所在的目录,但我需要将其写入与原始文件夹相同的位置。

我怀疑它与zipfile.ZipFile对象的功能有关,但是我似乎无法解决问题。任何帮助将不胜感激!谢谢!

import sys, zipfile, os, traceback, Tkinter, tkFileDialog

def zipws(path, zip, keep):
    path = os.path.normpath(path)
    print("Zipping {}...".format(path))

    for (dirpath, dirnames, filenames) in os.walk(path):

        for file in filenames:

            if not file.endswith('.lock'):
                try:
                    if keep:
                        zip.write(os.path.join(dirpath, file), os.path.join(os.path.basename(path), os.path.join(dirpath, file)[len(path)+len(os.sep):]))
                    else:
                        zip.write(os.path.join(dirpath, file), os.path.join(dirpath[len(path):], file))

                except Exception, e:
                    print("    Error adding {}: {}".format(file, e))

    return None

try:
    root = Tkinter.Tk()
    root.withdraw()
    root.attributes('-topmost', True)
    getGDBLoc = tkFileDialog.askdirectory(parent=root, initialdir="C:", title='Select the folder which contains the GDBs to be zipped')
    root.attributes('-topmost', False)
    wkPath = os.path.abspath(getGDBLoc).replace("\\","/")
    root.destroy()

    for fldr in os.listdir(wkPath):
        if fldr.endswith('.gdb'):
            outfile = fldr+".zip"
            try:
                zip = zipfile.ZipFile(outfile, 'w', zipfile.ZIP_DEFLATED)
                zipws(os.path.join(wkPath,fldr), zip, False)
                zip.close()
                print("  >> {} zipped successfully".format(outfile))

            except RuntimeError:
                if os.path.exists(outfile):
                        os.unlink(outfile)
                zip = zipfile.ZipFile(outfile, 'w', zipfile.ZIP_STORED)
                zipws(os.path.join(wkPath,fldr), zip, False)
                zip.close()
                print("  >> {} zipped, however unable to compress zip file contents.".format(outfile))

except:

    tb = sys.exc_info()[2]
    tbinfo = traceback.format_tb(tb)[0]
    print("PYTHON ERRORS:\nTraceback Info:\n{}\nError Info:\n    {}: {}\n".format(tbinfo, sys.exc_type, sys.exc_value))

1 个答案:

答案 0 :(得分:0)

发现错误。不出所料,我的问题是当我创建zipfile.ZipFile对象时。 Outfile必须是完整路径位置,而不仅仅是输出文件名。

更改了这些行:

zip = zipfile.ZipFile(os.path.join(wkPath,outfile), 'w', zipfile.ZIP_DEFLATED)

对此:

t = np.linspace(0,55*24*60*60, 55)
s = df.values
sns.set_style("darkgrid")
plt.ylabel("Amplitude")
plt.xlabel("Time [s]")
plt.plot(t, s)
plt.show()

我发誓我以前曾经尝试过,但是没有用,但是现在可以用了。