gpt4 book ai didi

python - 在python中压缩文件

转载 作者:太空狗 更新时间:2023-10-29 20:12:54 24 4
gpt4 key购买 nike

我的程序运行顺利,但我希望我的文件从 ftp 压缩到我的本地驱动器

问题是在调用我的 main() 函数后只有 1 个文件被压缩

这是我的代码:

import os
import upload
import download
import zipfile
import ConfigParser
import ftputil

def main():

#create a folder Temp on d drive for later use
path = r'D:\Temp'
os.mkdir(path)

#parse all the values at config.ini file
config = ConfigParser.ConfigParser()
config.readfp(open('config.ini'))
server = config.get('main', 'Server')
username = config.get('main', 'Username')
password = config.get('main', 'Password')
uploads = config.get('main', 'Upload folder')
downloads = config.get('main', 'Download folder')

#connect to ftp
ftp = ftputil.FTPHost(server, username, password)

dirlist = ftp.listdir(downloads)

for list in dirlist:
ftp.chdir(downloads)
target = os.path.join(path, list)
ftp.download(list, target)


#########################################################
# THis section is where algo fails but the program run#
########################################################

#zipping files
absolute_path = r'D:\Temp'
dirlist = os.listdir(absolute_path)
filepath = r'D:\Temp\project2.zip'
for list in dirlist:
get_file = os.path.join(absolute_path, list)
zip_name = zipfile.ZipFile(filepath, 'w')
zip_name.write(get_file, 'Project2b\\' + list)




if __name__ == '__main__':
print "cannot be"

最佳答案

当你这样做时:

for list in dirlist:
get_file = os.path.join(absolute_path, list)
zip_name = zipfile.ZipFile(filepath, 'w')
zip_name.write(get_file, 'Project2b\\' + list)

您为每个要压缩的文件重新创建一个 ZipFile,"w" 模式意味着您从头开始重新创建它。

试试这个(在循环之前创建 zip 文件):

zip_name = zipfile.ZipFile(filepath, 'w')
for list in dirlist:
get_file = os.path.join(absolute_path, list)
zip_name.write(get_file, 'Project2b\\' + list)

或者这样,它将以追加模式打开 zip 文件:

for list in dirlist:
get_file = os.path.join(absolute_path, list)
zip_name = zipfile.ZipFile(filepath, 'a')
zip_name.write(get_file, 'Project2b\\' + list)

关于python - 在python中压缩文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11240728/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com