【发布时间】:2020-09-03 09:39:13
【问题描述】:
最近开始学习python,有个问题....需要解压rar文件,有密码保护,但是密码写在文件名里,在存档里。等等~300次。如何,用什么以及在哪里可以实施? 比如有一个压缩包383442389.rar,它有两个文件,pass-1337643656.data(名字包含压缩包密码)和下面的压缩包)
【问题讨论】:
最近开始学习python,有个问题....需要解压rar文件,有密码保护,但是密码写在文件名里,在存档里。等等~300次。如何,用什么以及在哪里可以实施? 比如有一个压缩包383442389.rar,它有两个文件,pass-1337643656.data(名字包含压缩包密码)和下面的压缩包)
【问题讨论】:
我不确定你的问题的所有背景,但我会尽力回答你。
你说需要解压一个.rar文件,但这是不可能的,如果文件是.rar你需要解压
如果您只需要解压缩 .zip
类似的东西应该可以工作
from zipfile import ZipFile
with ZipFile('test1.zip', 'r') as myzip:
myzip.extractall(pwd='<password>')
pip install rarfile(仅在python 3中安装)
from rarfile import RarFile
with RarFile('test2.rar', 'r') as myrar:
myrar.extractall(pwd='<password>')
RarFile.namelist() 按名称返回存档成员列表。
所以你可以使用 split 提取密码
s = 'pass-1337643656.data'
s.split('-')[1].split('.')[0]
print(s)
'1337643656'
你也可以使用正则表达式来提取它
结论。
使用 .rar 的完整解决方案可能是
from rarfile import RarFile
with RarFile('test2.rar', 'r') as myrar:
file_names = myrar.namelist()
pass_file = list(filter(lambda k: 'pass' in k, l))[0]
pass = pass_file.split('-')[1].split('.')[0]
myrar.extractall(pwd=pass)
参考。
【讨论】:
RarFile('test2.rar', 'r') as myrar:``, I you read the referece that I let you regarding to rarfile you can see the specification of the constructor of the object RarFile, as you can see here rarfile.RarFile(file[, mode='r'])` 设置了相对于当前文件夹的路径,我在该行中有我的脚本``其中文件应该是文件的路径
pass_file..split ('-') [1] .split ('.') [0],可能是复制和粘贴错误,因为在答案中我没有看到那个错误,应该成为pass_file.split ('-') [1] .split ('.') [0]