Teracan
Teracan

Reputation: 105

Python tar.add files but omit parent directories

I am trying to create a tar file from a list of files stored in a text file, I have working code to create the tar, but I wish to start the archive from a certain directory (app and all subdirectories), and remove the parents directories. This is due to the software only opening the file from a certain directory.

package.list files are as below:

app\myFile app\myDir\myFile app\myDir\myFile2

If I omit the path in restore.add, it cannot find the files due to my program running from elsewhere. How do I tell the tar to start at a particular directory, or to add the files, but maintain the directory structure it got from the text file, e.g starting with app not all the parent dirs

My objective is to do this tar cf restore.tar -T package.list but with Python on Windows.

I have tried basename from here: How to compress a tar file in a tar.gz without directory?, this strips out ALL the directories.

I have also tried using arcname='app' in the .add method, however this gives some weird results by breaking the directory structure and renames loads of files to app

path = foo + '\\' + bar
file = open(path +  '\\package.list', 'r')
restore = tarfile.open(path +  '\\restore.tar', 'w')
for line in file:
    restore.add(path + '\\' + line.strip())
restore.close()
file.close()

Using Python 2.7

Upvotes: 3

Views: 6085

Answers (1)

luk32
luk32

Reputation: 16090

You can use 2nd argument for TarFile.add, it specified the name inside the archive.

So assuming every path is sane something like this would work:

import tarfile
prefix = "some_dir/"
archive_path = "inside_dir/file.txt"
with tarfile.open("test.tar", "w") as tar:
    tar.add(prefix+archive_path, archive_path)

Usage:

> cat some_dir/inside_dir/file.txt
test
> python2 test_tar.py
> tar --list -f ./test.tar
inside_dir/file.txt

In production, i'd advise to use appropriate module for path handling to make sure every slash and backslash is in right place.

Upvotes: 4

Related Questions