gpt4 book ai didi

python - 在Python中循环压缩zip文件

转载 作者:太空宇宙 更新时间:2023-11-03 20:10:02 24 4
gpt4 key购买 nike

我有一个数据框,其中包含学生 ID、姓名和其他信息。我已经对学生姓名(stu NAME)进行了分组,我需要为每个学生单独创建zip文件(基于学生姓名),然后将它们全部压缩。我可以压缩所有文件,但无法根据学生姓名压缩每个学生的个人资料。我只需要在循环中添加一行 after(out_file.write(csv)) 来压缩每个 csv 文件。

groupby = df_concat.groupby('stu_NAME')

for n,g in groupby:
csv=g.to_csv(index=false)

with open('{}{}.csv'.format(path,n),'w' as out_file:
out_file.write(csv)


shutil.make_archive('path1','zip', 'path2')

最佳答案

怎么样:

import pandas as pd
import zipfile

# Create a zip file
def create_zip(srcs, dst, filenames, op):
zf = zipfile.ZipFile(dst, op, zipfile.ZIP_DEFLATED)
for src, filename in zip(srcs, filenames):
zf.write(src, filename)
zf.close()

def main():
dct = {'stu_NAME': ['student_2', 'student_1'],
'other_info': [2, 1]}

df = pd.DataFrame(dct)

groupby = df.groupby(['stu_NAME'])

zip_all_zips = []
zip_all_csvs = []

for n,g in groupby:
csv=g.to_csv(index=False)
filename = '{}{}'.format('path_',n)
filename_csv = filename + '.csv'
filename_zip = filename + '.zip'
with open(filename_csv,'w') as out_file:
out_file.write(csv)
zip_all_zips.append(filename_zip)
zip_all_csvs.append(filename_csv)
# Create a zip file for each student
create_zip([filename_csv], filename_zip, [filename_csv], 'w')

# Create a zip file with all students (.zip of .zips)
create_zip(zip_all_zips, 'all_students_zip.zip', zip_all_zips, 'w')

# Create a zip file with all students (.zip of .csvs)
create_zip(zip_all_csvs, 'all_students_csv.zip', zip_all_csvs, 'w')

if __name__ == '__main__':
main()

产量

all_students_csv.zip  
path_student_1.csv
path_student_2.csv
all_students_zip.zip
path_student_1.zip
path_student_2.zip

它创建 (1) 每个 .csv 的 .zip,(2) 包含所有 .csv 的 .zip,以及 (3) 包含所有 .zip 的 .zip。所以你注释掉你不需要的东西。如果您想在创建 .zip 后删除 .csv,则可以执行以下操作:

import os
for filename_csv in zip_all_csvs:
os.remove(filename_csv)

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

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