开发者

Python tarfile module overwrites existing files during extraction - how to disable it?

开发者 https://www.devze.com 2023-01-19 13:39 出处:网络
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 cu

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])
0

精彩评论

暂无评论...
验证码 换一张
取 消