Say you unzip a file called file123.zip
with zipfile.ZipFile
, which yields an unzipped file saved to a known path. However, this unzipped file has a completely random name. How do you determine this completely random filename? Or is there some way to control what the name of the unzipped file is?
I am trying to implement this in python.

- 1,972
- 3
- 26
- 55

- 9
- 1
-
Doesn't the unzipped file have the same name as the zipped one? – DavidG Dec 22 '17 at 09:15
-
No, it does not. And what I meant to say was that the unzipped file name is completely arbitrary and not random, as @mhawke said below – iknowfrench Dec 22 '17 at 18:24
-
@iknowfrench: in that case, is there something about my answer that doesn't solve your problem? You can choose your own file name, and the file names are available in `namelist()`. – mhawke Dec 23 '17 at 00:32
-
@mhawke absolutely not, your code solved my problem perfectly! – iknowfrench Dec 24 '17 at 03:35
2 Answers
By "random" I assume that you mean that the files are named arbitrarily.
You can use ZipFile.read()
which unzips the file and returns its contents as a string of bytes. You can then write that string to a named file of your choice.
from zipfile import ZipFile
with ZipFile('file123.zip') as zf:
for i, name in enumerate(zf.namelist()):
with open('outfile_{}'.format(i), 'wb') as f:
f.write(zf.read(name))
This will write each file from the archive to a file named output_n
in the current directory. The names of the files contained in the archive are obtained with ZipFile.namelist()
. I've used enumerate()
as a simple method of generating the file names, however, you could substitute that with whatever naming scheme you require.

- 84,695
- 9
- 117
- 138
If the filename is completely random you can first check for all filenames in a particular directory using os.listdir(). Now you know the filename and can do whatever you want with it :)
See this topic for more information.

- 83
- 1
- 1
- 9