我想遍歷一個目錄。下面是代碼:Python遍歷文件系統。奇怪的問題
file_list = []
os.chdir(self.config.Root_Directory_Path())
for root, dirs, files in os.walk("."):
file_list.extend(join(root,f) for f in files)
file_sorted = sorted(file_list)
f = open(self.config.Client_Local_Status(),'wb')
for file in file_sorted:
print(file + "|" + str(os.path.getmtime(file)) + "\n")
f.close()
首先,我遍歷樹,然後對其進行排序然後打印出來。但是在遍歷時我得到了下面的錯誤。我很確定文件存在,但無法找出錯誤的原因。請幫助我找出錯誤和麻煩的原因。
以下是輸出。
輸出:
.\Drivers\Intel Drivers\Applications\Software\Applications\Wave_Embassy_Trust_Suite\EMBASSY Security Center\program files\Wave Systems Corp\EMBASSY Security Center\plugins\cpm.scp\webinterface\ru\js\HelpMessages.js|1229488128.0
.\Drivers\Intel Drivers\Applications\Software\Applications\Wave_Embassy_Trust_Suite\EMBASSY Security Center\program files\Wave Systems Corp\EMBASSY Security Center\plugins\cpm.scp\webinterface\ru\js\Strings.js|1229488128.0
成功地打印大量文件名後,代碼爲一個特定的文件,如下所示失敗:
錯誤:
Traceback (most recent call last):
File "C:\SyncClientRK\SyncClientRK.py", line 183, in <module>
SyncClientRK()
File "C:\SyncClientRK\SyncClientRK.py", line 17, in __init__
self.getStatus()
File "C:\SyncClientRK\SyncClientRK.py", line 38, in getStatus
self.generateLocalStatus()
File "C:\SyncClientRK\SyncClientRK.py", line 53, in generateLocalStatus
print(file + "|" + str(os.path.getmtime(file)) + "\n")
File "C:\Python33\lib\genericpath.py", line 54, in getmtime
return os.stat(filename).st_mtime
FileNotFoundError: [WinError 3] The system cannot find the path specified: '.\\Drivers\\Intel Drivers\\Applications\\Software\\Applications\\Wave_Embassy_Trust_Suite\\EMBASSY Security Center\\program files\\Wave Systems Corp\\EMBASSY Security Center\\plugins\\cpm.scp\\webinterface\\zh-CHS\\AccessingToolkit.htm'
請注意,該文件在循環中獲取並打印,但os.path.getmtime正在拋出一個找不到的錯誤。無法理解爲什麼以及如何解決這個問題。
我看到這是一個HTML文件。你有沒有嘗試在瀏覽器中打開它,看它是否真的存在?我的猜測是,當你調用'os.walk'時它可能已經存在,並且在你檢查修改時間時被刪除。 – mbatchkarov
@reseter當然,它是一個HTML文件。我用記事本和瀏覽器打開它,並在其中看到html內容。它也有一些中國人。但我認爲這也沒有關係,因爲我沒有閱讀其中的內容。它不會被刪除,因爲我沒有刪除它。我可以一直看到文件。遍歷之後和遍歷之後。請再猜一次嗎? – Romaan
你應該明確地捕捉到由於文件消失而導致的錯誤。 – Alfe