tar several folder and name them in python

To tar several folders and name them in Python, we can use the subprocess module to call the tar command with the appropriate arguments. Here's an example code:

main.py
import subprocess

# List of folder paths to be tarred
folders_to_tar = ['/path/to/folder1', '/path/to/folder2', '/path/to/folder3']

# Name of the output tar file
output_filename = 'archive.tar'

# Call the tar command with appropriate arguments
subprocess.run(['tar', '-cvf', output_filename] + folders_to_tar)
313 chars
11 lines

In the above code, we first define a list folders_to_tar consisting of the absolute paths of the folders that we want to tar. We also define the name of the output tar file as output_filename.

We then call the subprocess.run method with the command and arguments to execute. Here we use the tar command with the -cvf arguments to create a tar file named output_filename and pass in the folders_to_tar list as additional arguments to tar them together.

Note that the full paths of the folders need to be provided and that the Python script needs suitable file permissions to write to the directory/folder where it wants to create the output tar file.

gistlibby LogSnag