2012-12-04 72 views
1

我試圖編寫一些遞歸搜索路徑和子目錄中以「FFD8」十六進制值開頭的文件。在運行腳本時,我已經將它與參數參數中指定的位置一起使用,但是當它需要移動到子目錄時會出現問題。在python中使用os.walk更改目錄

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是桌面上的一個子文件夾內。任何人都可以通過最簡單的方式來改變目錄,以便它可以繼續掃描子目錄而不會出現問題嗎?謝謝!

+0

小細節:這將是較好的去除行'數據= f.read(2)',取而代之的if語句'如果f.read (2)=='\ xff \ xd8':'。它實際上是相同的,只是它不執行十六進制編碼的事情。 – Robin

回答

4

您需要使用絕對文件路徑才能打開它們,但files僅列出沒有路徑的文件名。但是,root變量確實包含當前目錄的路徑。

使用os.path.join加入二:

for root, dir, files in os.walk(str(sys.argv[1])): 
    for fp in files: 
     f = open(os.path.join(root, fp), 'rb') 
+0

完美!正是我所需要的,現在工作。 :) – FrostyX