我想遍历一个目录。下面是代码: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