Python 如何在解压tar文件后检查那里有什么

Python 如何在解压tar文件后检查那里有什么,python,tar,unzip,Python,Tar,Unzip,所以,我正在编写一个python脚本,它将打开一个tar文件,如果其中有一个目录,我的脚本将打开该目录并检查文件 E = raw_input("Enter the tar file name: ") // This will take input from the user tf = tarfile.open(E) // this will open the tar file 现在,检查“tf”的最佳方法是是否有目录?与其到我的终端去做ls,我想在解压tar后用相同的python脚本检查是否有

所以,我正在编写一个python脚本,它将打开一个tar文件,如果其中有一个目录,我的脚本将打开该目录并检查文件

E = raw_input("Enter the tar file name: ") // This will take input from the user
tf = tarfile.open(E) // this will open the tar file

现在,检查“tf”的最佳方法是是否有目录?与其到我的终端去做ls,我想在解压tar后用相同的python脚本检查是否有目录。

在python中,可以使用os.path.exists(f)命令检查路径是否存在,其中f是文件名及其路径的字符串表示:

import os

path = 'path/filename'

if os.path.exists(path):
    print('it exists')
编辑:

tarfile对象有一个方法“getnames()”,它给出tar文件中所有对象的路径

paths = tf.getnames() #returns list of pathnames
f = paths[1] #say the 2nd element in the list is the file you want

tf.extractfile(f)

假设目录“S3”中有一个名为“file1”的文件。那么tf.getnames()的一个元素将是'S3/file1'。然后你可以提取它。

但是我正在打开一个tar文件,我想检查里面是否有任何东西。假设我打开一个tar文件,它得到一个目录“S3”。我要打开“S3”。如何在Python脚本中实现这一点。getnames()提供tar对象中所有文件的路径,然后您可以使用extractfile()提取它们