简体   繁体   English

如何使用python读取多个.tar文件

[英]How to read multiple .tar files using python

So i'm trying to read a .tar file, it works fine but sometimes the filename is a bit different.所以我正在尝试读取 .tar 文件,它工作正常,但有时文件名有点不同。 The filename sometimes changes from filename_01.tar to filename_02.tar I have tried using filename_*.tar but that doesn't seem to work.文件名有时会从filename_01.tar更改为filename_02.tar我曾尝试使用filename_*.tar但这似乎不起作用。

I know it's a basic question but I can't figure it out.我知道这是一个基本问题,但我无法弄清楚。

My code: (using python 3.7+)我的代码:(使用python 3.7+)

import tarfile

tar = tarfile.open('filename_01.tar')
tar.extractall('locationfolder')
tar.close

* isn't expanded by tar command. *没有被tar命令扩展。 You can create a loop with glob.glob on the required pattern.您可以使用glob.glob在所需模式上创建循环。 Also, better use with syntax to open the file, so there's no typo when calling tar.close without parentheses, which does nothing.此外,更好地利用with语法打开文件,所以没有错字时调用tar.close没有括号,这什么都不做。

import tarfile,glob

for f in glob.glob('filename_*.tar'):
   with tarfile.open(f) as tar:
       tar.extractall('locationfolder')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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