0

それで、私はtarファイルを開くpythonスクリプトを書いています。その中にディレクトリがある場合、私のスクリプトはそのディレクトリを開いてファイルをチェックします...

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 スクリプトで何かを実行したいと考えています。

4

1 に答える 1

0

Python では、os.path.exists(f) コマンドを使用してパスが存在するかどうかを確認できます。ここで、f はファイル名とそのパスの文字列表現です。

import os

path = 'path/filename'

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

編集:

tarfile オブジェクトには、tar ファイル内のすべてのオブジェクトのパスを提供する「getnames()」メソッドがあります。

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() の要素の 1 つが'S3/file1'になります。その後、それを抽出できます。

于 2013-06-18T22:52:52.200 に答える