使用结果的 os.listdir 和 os.stat 时出现 WindowsError

WindowsError when using os.listdir and os.stat of the result

我有以下代码片段可以获取文件的时间戳。

files_list = os.listdir(os.path.join(path, folder))
     for files in files_list:
     stats = os.stat(os.path.join(path, folder, files))

我是否有可能遇到以下错误,因为它无法找到它刚刚在 listdir 中获得的文件,这似乎违反直觉,当然除了我怀疑的竞争条件之外在这种情况下。

WindowsError: [Error 2] The system cannot find the file specified:
'\\sftp-server.domain.com\homes\server\location\FOLDER\FILE.PDF'

我也想知道域 lookup/temporary 网络问题是否会导致此错误?例如

\sftp-server.domain\homes\server\location\FOLDER

\sftp-server.domain\homes\server\location\FOLDER\FILE

只是URL个字符串,与真正的文件系统遍历无关。

想必FOLDERFILE不是真名吧?仔细查看 WindowsError 报告的文件名。如果它们在最后一个组件中包含问号,则 Unicode 文件名有问题。具体来说,当目录包含的文件名中包含无法在当前代码页中表示的 Unicode 字符(例如西欧或东欧语言环境中的日文字符)时,os.listdir 将 return 包含无法表示的 Unicode 字符的文件名转换为 ?。显然,这种本质上损坏的名称不能传递给 IO 函数,例如 openos.stat.

要解决此问题,请通过将目录作为 Unicode 字符串传递给 os.listdir 来请求 Unicode 文件名。这些将包含正确的字符并可以传递给 os.stat,它将在内部调用宽 API:

dirname = unicode(os.path.join(path, folder), 'mbcs')
file_list = os.listdir(dirname)
for filename in file_list:
    stats = os.stat(os.path.join(dirname, filename))
    # ...

服务器正在执行多线程,我们在单个 Javascript 方法中向同一文件夹资源发送多个 Ajax 请求。

如果首先处理 os.listdir,则会出现此错误,因为通过 SFTP 执行它需要很长时间。在此期间,os.remove 发生在另一个请求中,并删除了显示在 os.listdir 结果中的文件。在使他 os.listdir 作为适当的回调函数后,它工作得很好。