Reputation: 11
I am trying to unzip a file and extract all to the target directory. But it is giving me an error. Trying this small piece of code for a few days. Running into multiple errors. This code was working in the morning and now it is giving me this error.
Code:
def main():
file_name = 'D:\\BR_Files\\DDD_XXX_08042019_D.zip'
target_dir = 'D:\\BR_Files'
pswd = '123456'
pwd = bytes(pswd, 'utf-8')
with pyzipper.AESZipFile(file_name) as parent_file:
f.pwd = pwd
list_files = parent_file.namelist()
parent_file.extractall(target_dir)
child_file = list_files[0]
print(child_file)
with pyzipper.AESZipFile(target_dir+'\\'+child_file[0]) as newfile:
# extracting the zip
print(True)
newfile.extractall(target_dir)
parent_file.close()
newfile.close()
if __name__ == '__main__': main()
Complete trace back:
ValueError Traceback (most recent call last) <ipython-input-302-b9e455d215cb> in <module>
26 newfile.close()
27
---> 28 if __name__ == '__main__': main()
<ipython-input-302-b9e455d215cb> in main()
13 list_files = parent_file.namelist()
14
---> 15 parent_file.extractall(target_dir)
16
17 child_file = list_files[0]
~\Anaconda3\lib\site-packages\pyzipper\zipfile.py in extractall(self, path, members, pwd) 2093 2094 for zipinfo in members:
-> 2095 self._extract_member(zipinfo, path, pwd) 2096 2097 @classmethod
~\Anaconda3\lib\site-packages\pyzipper\zipfile.py in
_extract_member(self, member, targetpath, pwd) 2146 return targetpath 2147
-> 2148 with self.open(member, pwd=pwd) as source, \ 2149 open(targetpath, "wb") as target: 2150 shutil.copyfileobj(source, target)
~\Anaconda3\lib\site-packages\pyzipper\zipfile.py in open(self, name, mode, pwd, force_zip64) 1975 if not self.fp: 1976 raise ValueError(
-> 1977 "Attempt to use ZIP archive that was already closed") 1978 1979 if not pwd:
ValueError: Attempt to use ZIP archive that was already closed
Should be able to unzip a file to a target directory.
Upvotes: 0
Views: 6523
Reputation: 74655
The issue is that you are accessing parent_file
after the with
statement has finished.
You need to indent your code so that all accesses to a name bound by the as
clause of the with
statement are within the with
statement.
That is to say that your code should look more like this:
def main():
file_name = 'D:\\BR_Files\\DDD_XXX_08042019_D.zip'
target_dir = 'D:\\BR_Files'
pswd = '123456'
pwd = bytes(pswd, 'utf-8')
with pyzipper.AESZipFile(file_name) as parent_file:
f.pwd = pwd
list_files = parent_file.namelist()
parent_file.extractall(target_dir)
child_file = list_files[0]
print(child_file)
with pyzipper.AESZipFile(target_dir+'\\'+child_file[0]) as newfile:
# extracting the zip
print(True)
newfile.extractall(target_dir)
if __name__ == '__main__': main()
Note that I have not tested this code.
Also no need to close the parent_file
or newfile
as the with
statement does that automatically.
Upvotes: 3