1

I have a folder that contains zip files. I want to be able to unzip them, and specify "A[ll]" when asked "replace file.diz".

My current code is:

import os
import subprocess

os.chdir("path-to-directory")
for i in os.listdir():
    if i.endswith("zip"):
        subprocess.run("unzip '*.zip'", shell=True)

At this point I am asked:

Archive:  archivea.zip
replace file.diz? [y]es, [n]o, [A]ll, [N]one, [r]ename: 

What Python command can I use to specify A as input when Bash returns that question? Or, if I want to specify y as input (when the Bash command gets to archiveb.zip), how do I do that each time automatically in Python? Thank you.

ktb
  • 35
  • 5
  • You shouldn't put `*.zip` inside quotes, that prevents expanding the wildcard. – Barmar Jun 09 '23 at 15:09
  • Why not just use a python package to unzip the files? [Here's](https://stackoverflow.com/questions/3451111/unzipping-files-in-python) an example – ShadowCrafter_01 Jun 09 '23 at 15:11
  • 2
    You can use the `-o` option to force overwriting files without asking. – Barmar Jun 09 '23 at 15:18
  • BTW, `subprocess.run(['unzip', '*.zip'])` simplifies everything -- no quotes, no `shell=True`, no copy of `/bin/sh` being invoked at runtime. @Barmar, the intent is to have `unzip` itself expand the wildcard here; otherwise the first argument is treated as a zip file name and other arguments as names of files within that zip file to expand. – Charles Duffy Jun 09 '23 at 15:34

1 Answers1

1

As Barmar said in the comments, you can specify -o option to unzip:

-o overwrite existing files without prompting. This is a dangerous option, so use it with care. (It is often used with -f, however, and is the only way to overwrite directory EAs under OS/2.)

In general, if you want to specify a response you can use pexpect libary

Charles Duffy
  • 280,126
  • 43
  • 390
  • 441
Andrei Evtikheev
  • 331
  • 2
  • 12