Python tarfile module overwrites existing files during extraction - how to disable it?
Is there a way prevent tarfile.extractall
(API) from overwriting existing files? By "p开发者_StackOverflow社区revent" I mean ideally raising an exception when an overwrite is about to happen. The current behavior is to silently overwrite the files.
You could check result of tarfile.getnames
against the existing files and raise your error.
Have you tried setting tarfile.errorlevel
to 2? That will cause non-fatal errors to be raised. I'm assuming an overwrite falls in that category.
I have a similar situation, where I only want to extract if all the files have not yet already been extracted. I use the following function to check if archive
has already been extracted to extract_dir
:
from pathlib import Path
import tarfile
def is_extracted(archive, extract_dir):
tar = tarfile.open(archive)
filenames = tar.getnames()
return all([(Path(extract_dir) / f).exists() for f in filenames])
精彩评论