簡體   English   中英

在python中使用os.walk更改目錄

[英]Change directory using os.walk in python

我正在嘗試編寫一些遞歸搜索路徑和子目錄的文件,以十六進制值“FFD8”開頭。 我已經讓它在運行腳本時使用參數參數中指定的位置,但是當它需要移動到子目錄時就會出現問題。

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在桌面上的子文件夾中。 任何人都可以輕松地更改目錄的最簡單方法,以便它可以繼續掃描子目錄沒有問題嗎? 謝謝!

您需要使用絕對文件路徑來打開它們,但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')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM