2015-01-08 34 views
0

我有下面的zip文件。該文件正確地壓縮,但包含zip內的文件夾。我怎樣才能壓縮文件,同時仍然能夠顯示文件的位置?防止將zipfile寫入目錄以進行存檔

create_zip_path = "folder1\\folder2\\my_zip.zip" 
file_to_add_to_zip = "folder1\\folder2\\my_file.txt" 

zip_file(create_zip_path, file_to_add_to_zip) 


def zip_file(create_zip_path, file_to_add_to_zip): 
    import zipfile 
    try: 
     import zlib 
     compression = zipfile.ZIP_DEFLATED 
    except: 
     compression = zipfile.ZIP_STORED 

    modes = { zipfile.ZIP_DEFLATED: 'deflated', 
       zipfile.ZIP_STORED: 'stored', 
       } 

    zf = zipfile.ZipFile(create_zip_path, mode='w') 
    zf.write(file_to_add_to_zip, compress_type=compression) 

回答

1

您可以使用os模塊更改您的工作目錄。這應該工作:

import os 

print os.getcwd() #Your current working directory 
os.chdir(os.getcwd() + '/folder1/folder2/') 
print os.getcwd() #Your new wordking dir 

create_zip_path = "my_zip.zip" 
file_to_add_to_zip = "my_file.txt" 

zip_file(create_zip_path, file_to_add_to_zip) 
+0

完美工作。謝謝! – samg86