Different name of unpacked tar.gz folder using tarfile.extractall()

流过昼夜 提交于 2019-12-11 12:33:40

问题


I am using pythons tarfile.extractall() to unpack a foo.tar.gz file. I want to access the extracted folder, but sometimes the extracted folder has a different name than the packed file. I need a way to control the name of the extracted folder or, a return value that tells me the name of the extracted folder.

Example

packed file: foo-rc-2.0.0.tar.gz

unpacked folder: foo-2.0.0-rc


回答1:


tarfile.extractall() simply extracts all the files in the tarball to the current directory, or a directory of your choice.

If the tarball contains files with a nested directory structure, then that's what'll be extracted. It is that directory structure that you see. The names of these directories (there can be more than 1) do not have to correspond with the name of the tarball.

If you need to move these extracted contents, do so in a new and empty directory, so that you can just pick up everything in that directory:

os.mkdir('extraction')
tarball.extractall('extraction')
for name in os.listdir('extraction'):
     # move that name.



回答2:


You can use .getnames() to list the contents of the tarfile obj.



来源:https://stackoverflow.com/questions/32952260/different-name-of-unpacked-tar-gz-folder-using-tarfile-extractall

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!