简体   繁体   中英

Python: Delete file from the TAR archive using tarfile

Is it possible to remove from a TAR archive some file using tarfile ?

For example:

If an x.tar file includes the files a.txt , b.txt and c.txt , is it possible to remove a.txt ?

In other words: does any python solution exist to achieve something like this:

tar -vf x.tar --delete a.txt ?

Not with tarfile directly, although there may be some other library out there. A quick hack you can do is to extract the files, then recreate the tar minus the files you want to delete.

I had a similar problem and ended up using the 7z Command Line ( 7za.exe ), since it supports more functions than Python's tarfile , including deleting files from archive.

The downside of this solution is that you need to carry the 7za.exe file around with the program.

In your case, you could use something like

os.system("7za d x.tar a.txt")

Do however keep in mind that os.system is deprecated and you should use subprocess . Never used it, so I can't really help more.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM