【问题标题】:What algorithm is needed to extract the zip and rename a folder with a search inside that folder for a specific file? [closed]需要什么算法来提取 zip 并重命名文件夹,并在该文件夹中搜索特定文件? [关闭]
【发布时间】:2023-03-19 21:09:01
【问题描述】:

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

【问题讨论】:

  • 如果您在自己解决此问题时遇到特定问题,可以在此处使用您的代码询问。

标签: python zip


【解决方案1】:

试试这个重命名:

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)

【讨论】:

  • 非常感谢您的回复!万分感激!
【解决方案2】:

我建议使用shutil 模块来做一些这样的事情。要提取 .zip 文件:shutil.unpack_archive("my_file.zip", "extract_to")。制作 zip 存档:shutil.make_archive("zip_path_and_name", "zip", "/dir/to/pack/into/archive").

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

查找文件有点困难。根据.mod 文件在您的zip 存档中的位置,您可以使用os.listdir("/dir/that/the_file/is/in/"),它返回给定目录中文件和目录的列表。然后,您可以遍历此列表,检查文件是否以“.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)

【讨论】:

  • @Razilator:您真的应该尝试自己编写代码,然后如果出现问题,请用您失败的代码发布您的问题。
  • 非常感谢您的回复!万分感激!
猜你喜欢
  • 1970-01-01
  • 2013-12-14
  • 1970-01-01
  • 2022-01-24
  • 1970-01-01
  • 1970-01-01
  • 2023-03-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多