简体   繁体   English

无法打开 os.listdir 返回的文件

[英]Unable to open files returned by os.listdir

I have some code like this:我有一些这样的代码:

import os
directory = 'H:\\path\\to\\files'
for file in os.listdir( directory ):
  open( os.path.join( directory, file ) )

In a very small number of cases, running this code on a directory will throw the following error.在极少数情况下,在目录上运行此代码会引发以下错误。

IOError: [Errno 2] No such file or directory: 'H:\\path\\to\\files\\blahblah.file'

This doesn't happen for every file in the directory - the first few are opened correctly, but then it will fail on one of the files, the same each time.目录中的每个文件都不会发生这种情况 - 前几个文件正确打开,但随后它会在其中一个文件上失败,每次都相同。

The files in question do exist, so it's a problem with open rather than with os.listdir .有问题的文件确实存在,所以这是open而不是os.listdir的问题。

Strangely, changing the working directory and changing directory to be the corresponding relative path makes a difference to which file we fail on.奇怪的是,将工作目录和将directory更改为相应的相对路径会影响我们在哪个文件上失败。

I am running Python 2.7 on Windows 10.我在 Windows 10 上运行 Python 2.7。

Update It seems to be connected to the length of the file names.更新它似乎与文件名的长度有关。 The file names are very long in general: if I rename the file to something shorter, then it succeeds;文件名通常很长:如果我将文件重命名为更短的名称,那么它会成功; longer and it fails again.更长的时间,它再次失败。 That might explain why we were failing at different points when using a longer relative path.这可以解释为什么我们在使用更长的相对路径时会在不同的点上失败。

This seems to have been caused by the 260-character path length limit .这似乎是由 260 个字符的路径长度限制引起的。 The files that were failing had paths over 260 characters long.失败的文件的路径长度超过 260 个字符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM