0

所以,我正在编写一个 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 我想在同一个 python 脚本中做一些事情来检查解压缩 tar 后是否有一个目录。

4

1 回答 1

0

在 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'。然后你可以提取它。

于 2013-06-18T22:52:52.200 回答