简体   繁体   English

使用 Python3 从特定文件夹中提取并重命名 zip 文件

[英]Extract and rename zip file from specific folder using Python3

I am using python3.10.我正在使用python3.10。 To unzip a file I have a zip file in folder 'wowo' if I select folder using path and use only file name the code doesn't work.要解压缩文件,我在文件夹“wowo”中有一个 zip 文件,如果我使用路径的 select 文件夹并仅使用文件名,则代码不起作用。 But, when full path+filename given it works.但是,当给出完整路径+文件名时,它可以工作。 I don't want go give full path and file name together.我不希望 go 一起给出完整路径和文件名。 I want to define path saperately.我想单独定义路径。

zipdata = zipfile.ZipFile('/Volumes/MacHD/MYPY/wowo/NST_cm.zip')
    zipinfos = zipdata.infolist()
    for zipinfo in zipinfos:
    zipinfo.filename = 'Nst.csv'
    zipdata.extract(path=path, member=zipinfo)

You could join the two strings in order to form the full filepath.您可以连接这两个字符串以形成完整的文件路径。

filepath = os.path.join(path, filename)
zipfile.ZipFile(filepath)

Or I believe the ZipFile function can take a path and file name expression like this或者我相信 ZipFile function 可以采用这样的路径和文件名表达式

zipfile.ZipFile(path,'filename')

Replacing filename with the name of the file you wish to work with用您希望使用的文件名替换文件名

You can use pathlib and add the path with the filename in the zipfile.zipfile:您可以使用 pathlib 并在 zipfile.zip 文件中添加带有文件名的路径:

import pathlib
path = pathlib.Path('PATH/TO/FOLDER')

zipfile.ZipFile( path / 'filename')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM