提取 zip 文件并重命名文件夹并在该文件夹内搜索特定文件需要什么算法?

What algorithm is needed to extract the zip and rename a folder with a search inside that folder for a specific file?

我对Python了解不多。为以下提示正确的代码算法:我正在下载一个 zip 文件。我需要将它解压到 some_name 文件夹,然后进入该文件夹并找到扩展名为 .mod 的文件并选择其名称,然后将 some_name 文件夹重命名为该名称来自 .mod 并将其打包回存档中。海狸对大家好!

我建议使用 shutil module 来完成其中的一些工作。要提取 .zip 文件:shutil.unpack_archive("my_file.zip", "extract_to")。要制作 zip 存档:shutil.make_archive("zip_path_and_name", "zip", "/dir/to/pack/into/archive").

os module 有一些功能可以帮助您查找和重命名文件。重命名文件或目录:os.rename("/old/file/name", "/new/file/name")

查找文件有点困难。根据 .mod 文件在 zip 存档中的位置,您可以使用 os.listdir("/dir/that/the_file/is/in/"),其中 returns 是给定目录中文件和目录的列表。然后您可以遍历此列表,检查文件是否以“.mod”结尾。例如:

for file in os.listdir("/dirname/"):
    if file.endswith(".mod"):
        do_something()

这是一个例子。将路径名替换为您正在使用的路径名:

import os
import shutil

# Unpack the archive to a directory
shutil.unpack_archive("/archive/to/unpack", "/dir/that/contains/old_dir_name")

# Look in the directory for the .mod file
for file in os.listdir("/dir/that/contains/old_dir_name/"):
    if file.endswith(".mod"):
        file_name = file.replace(".mod", "")

# Rename the directory according to the file name
os.rename("/dir/that/contains/old_dir_name/", "/dir/that/contains/" + file_name)

# Repack the archive
shutil.make_archive("/archive/to/create", "zip", "/dir/that/contains/" + file_name)

重命名试试这个:

import zipfile
from io import BytesIO
import os

### if you have zip archive in file
z=zipfile.ZipFile('your.zip')
### if you have zip archive in bytes
z=zipfile.ZipFile(BytesIO(your_bytes))
### extract to some_name
z.extractall('some_name')
### iterate through file names
for name in z.filelist:
    if name.endswith('.mod'):
        break
### split extension
bare=os.path.splitext(name)[0]
os.rename('some_name',bare)

这用于打包成 zip 存档

newz=zipfile.ZipFile('new.zip','w')
for q in os.path.listdir(bare):
    newz.write(os.path.join(bare,q))
newz.close()    

你真的不需要解压 zip 文件,如果你只想重命名你的文件夹,使用这个:


for name in z.filelist:
    if name.endswith('.mod'):
       break
os.rename('some_name',name)