Search code examples
pythontarfile

How to avoid overwrite of files


we are using tarFile library of python to untar the set of given files to the target directory.

tarGzipFile = tarfile.open(fileName)
tarGzipFile.extractall(targetDir + '/')

Here if same file exists in more than one tar.gz file then the file is over writing in the target directory. How can i change my code to avoid the overwrite? and also looking for the option similar to tar --backup none or numbered...so that if file exists then it prefix with ~ or add number at the end.


Solution

  • You can use tarGzipFile.getmembers() to list the files in the archive, and pass members= to extractall with only those files you wish to extract (i.e., excluding files already existing). os.path.exists( ) can be used to check for file existence.