python 如何压缩以特定扩展名结尾的文件

iezvtpos  于 2023-02-02  发布在  Python
关注(0)|答案(3)|浏览(144)

我想获取以.npy或csv结尾的目录中的所有文件(我在执行了几次for循环后到达了该目录-因此是fourth.path),然后压缩这些文件。我的代码运行时只将一个文件放入zip文件中。我做错了什么?我尝试更改缩进,但没有创建zip文件

import json
import os
import zipfile
import zlib

directory = os.path.join(os.getcwd(), 'recs')
radarfolder = 'RadarIfxAvian'
file = os.listdir(directory)

def r(p, name):
    p = os.path.join(p, name)
    return p.replace("/", "\\") 

#This code will list all json files in e    ach file
for first in os.scandir(directory):
    if first.is_dir():
        for second in os.scandir(first.path):
            if second.is_dir():
               for third in os.scandir(second.path):
                if third.is_dir():
                    radar_folder_name = ''
                    list_files = ()
                    for fourth in os.scandir(third.path):
                        if fourth.is_dir():
                            if radarfolder in fourth.path:
                                radar_folder_name = fourth.path
                                print(radar_folder_name)
                                list_files = ()
                                for file in os.listdir(fourth.path):
                                    if file.endswith(".npy") | file.endswith(".csv"):
                                        list_files = (file)
                                        print(list_files)
                                    with zipfile.ZipFile(radar_folder_name +'\\' +'radar.zip', 'w', compression=zipfile.ZIP_DEFLATED ) as zipMe:
                                        zipMe.write(radar_folder_name +'\\' +list_files)            
                                        zipMe.close()

我尝试更改缩进,导致错误:TypeError:只能将str(而不是“tuple”)连接到str或未创建zip文件

gpnt7bae

gpnt7bae1#

正如我在第二条评论中所说的,你的问题来自于你的压缩语句中的'w'参数。它导致了每次打开zip文件时都被覆盖,你压缩每个文件时都会这样做。你可以用两种方法来解决这个问题(至少):

  • 将“w”改为“a”;这样,文件将被附加到你的压缩文件中(副作用是,如果你多次这样做,文件将被添加不止一次)。
  • 保留“w”,但是只打开一次zip,之前已经列出了所有你想压缩的文件。参见下面我的代码。

我冒昧地重写了代码中查找“RadarIfxAvian”文件夹的部分,因为嵌入式for很笨拙(如果文件夹结构发生变化,它们可能无法工作),将其替换为多用途递归函数。
请注意,文件夹结构将包含在.zip中;如果你只想压缩文件本身,考虑在压缩文件之前执行os.chdir(radar_folder_name)

# This function recursively looks for the 'filename' file or folder
# under 'start_path' and returns the full path, or an empty string if not found.
def find_file(start_path, filename):
    if filename in os.listdir(start_path):
        return start_path + '/' + filename
    for file in os.scandir(start_path):
        if not file.is_dir():
            continue
        if (deep_path:=find_file(start_path + '/' + file.name, filename)):
            return deep_path
    return ''

directory = os.path.join(os.getcwd(), 'recs')
radarfolder = 'RadarIfxAvian'

radar_folder_name = find_file(directory, radarfolder)
print(radar_folder_name)
list_files = []
for file in os.listdir(radar_folder_name):
    if file.endswith(".npy") or file.endswith(".csv"):
        list_files.append(file)
with zipfile.ZipFile(radar_folder_name + '/' + 'radar.zip', 'w', compression=zipfile.ZIP_DEFLATED ) as zipMe:
    for file in list_files:
        zipMe.write(radar_folder_name + '/' + file)
pqwbnv8z

pqwbnv8z2#

如果我对代码的理解正确的话,您正在查找一个文件夹“RadarIfxAvian”,并希望在该文件夹中放置一个.ZIP文件,其中包含该目录中的任何.CSV或.NPY文件,这应该与使用os.walk进行递归搜索等效:

import os
import zipfile

for path, dirs, files in os.walk('recs'):
    if os.path.basename(path) == 'RadarIfxAvian':
        print(path)
        with zipfile.ZipFile(os.path.join(path, 'radar.zip'), 'w', zipfile.ZIP_DEFLATED) as zip:
            for file in files:
               if file.endswith(".npy") | file.endswith(".csv"):
                   print(file)
                   zip.write(file)
        break  # stop search once the directory is found and processed
2izufjch

2izufjch3#

我使用以下步骤调整了代码:
1.将if放入函数中
1.通过循环遍历我追加的列表中的每一项来编写zip

import json
import os
import glob
import zipfile
import zlib

directory = os.path.join(os.getcwd(), 'recs')
radarfolder = 'RadarIfxAvian'
file = os.listdir(directory)
list_files = []

def r(p, name):
    p = os.path.join(p, name)
    return p.replace("/", "\\") 

def tozip(path, file):
    filestozip = []
    if file.endswith(".npy") or file.endswith(".csv"):
        filestozip = (path + '\\' + file)
        list_files.append(filestozip)
    return list_files

#This code will list all json files in each file
for first in os.scandir(directory):
    if first.is_dir():
        for second in os.scandir(first.path):
            if second.is_dir():
               for third in os.scandir(second.path):
                if third.is_dir():
                    radar_folder_name = ''
                    filestozip = []
                    list_files.clear()
                    for fourth in os.scandir(third.path):
                        if fourth.is_dir():
                            if radarfolder in fourth.path:
                                radar_folder_name = fourth.path
                                for file in os.listdir(fourth.path):
                                    filestozip = tozip(radar_folder_name,file)
                                print(filestozip)
                                ZipFile = zipfile.ZipFile(r(radar_folder_name,"radar.zip"), "w")
                                for a in filestozip:
                                    ZipFile.write(a, compress_type= zipfile.ZIP_DEFLATED)
                                    print(radar_folder_name + "added to zip")

相关问题