Septiana Fajrin
Septiana Fajrin

Reputation: 115

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)

Upvotes: -1

Views: 63

Answers (3)

Pathum Rathnayaka
Pathum Rathnayaka

Reputation: 1

You'll need to make changes to your script so that it references the folder where the file extraction script is located in order to execute it. By providing the folder path as a parameter, you may use os.listdir() to list the files in the particular folder.

Upvotes: 0

delphisharp
delphisharp

Reputation: 111

example: tar -xf a.tar.gz -C /opt

man tar see: To move file hierarchies, invoke tar as tar -cf - -C srcdir . | tar -xpf - -C destdir

Upvotes: 0

Seth.TW
Seth.TW

Reputation: 36

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]

Upvotes: 0

Related Questions