pythonwindowsextracttaros.system

Run Python script to Extract file in different folder


I have trouble with my Python script. Currently, my script works to run the script which is file and myscript.py in the same folder. I want to run myscript.py to extract files in another folder.

topology enter image description here

myscript.py

import os
import re

# Setup main paths.
myfiles = os.listdir()

pattern = re.compile(r"filesextract\d+")

for files in myfiles:
    if(pattern.match(files) != None):
        command = "tar -xzvf " + files
        os.system(command)

Solution

  • make the script accept input and output directory (extraction) as arguments (or envs), or find a better approach to set these depending on your scenario, so that you can run the script from any location.

    if len(sys.argv) < 3:
        print("Usage: python myscript.py <input_directory> <output_directory>")
        sys.exit(1)
    
    # Get the input and output directories from the arguments
    input_directory = sys.argv[1]
    output_directory = sys.argv[2]