我試圖編寫一些遞歸搜索路徑和子目錄中以「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是桌面上的一個子文件夾內。任何人都可以通過最簡單的方式來改變目錄,以便它可以繼續掃描子目錄而不會出現問題嗎?謝謝!
小細節:這將是較好的去除行'數據= f.read(2)',取而代之的if語句'如果f.read (2)=='\ xff \ xd8':'。它實際上是相同的,只是它不執行十六進制編碼的事情。 – Robin