1

「FFD8」の16進値で始まるファイルのパスとサブディレクトリを再帰的に検索するものを作成しようとしています。スクリプトの実行時に引数パラメーターで指定された場所で動作するようになりましたが、サブディレクトリに移動する必要があるときに問題が発生します。

import string, sys, os
 os.chdir(sys.argv[1])
 for root, dir, files in os.walk(str(sys.argv[1])):
         for fp in files:
             f = open(fp, 'rb')
             data = f.read(2)
             if "ffd8" in data.encode('hex'):
                 print "%s starts with the offset %s" % (fp, data.encode('hex'))
             else:
                 print "%s starts wit ha different offset" % (fp)

os.chdir コマンドを使用する必要がある理由はわかりませんが、何らかの理由でそれがないと、デスクトップからスクリプトを実行すると、パラメーターが無視され、パスに関係なく常にデスクトップ ディレクトリから検索が実行されます。特定。

これからの出力はautodl2.cfg starts wit ha different offset DATASS.jpg starts with the offset ffd8 IMG_0958.JPG starts with the offset ffd8 IMG_0963.JPG starts with the offset ffd8 IMG_0963_COPY.jpg starts with the offset ffd8 project.py starts wit ha different offset Uplay.lnk starts wit ha different offset Traceback (most recent call last): File "C:\Users\Frosty\Desktop\EXIF PROJECT\project2.py", line 15, in <module> f = open(fp, 'rb') IOError: [Errno 2] No such file or directory: 'doc.kml'

ここでエラーが発生する理由がわかりました。ファイル doc.kml がデスクトップのサブフォルダー内にあるためです問題なくサブディレクトリのスキャンを続行できるように、ディレクトリを変更する最も簡単な方法を誰かが明らかにすることはできますか? ありがとう!

4

1 に答える 1

4

それらを開くには絶対ファイルパスを使用する必要がありfilesますが、パスなしでファイル名のみをリストします。ただし、root変数には現在のディレクトリへのパスが含まれています。

os.path.join2 つを結合するために使用します。

for root, dir, files in os.walk(str(sys.argv[1])):
    for fp in files:
        f = open(os.path.join(root, fp), 'rb')
于 2012-12-04T18:18:58.777 に答える