如何处理 OSError: \[Errno 20\] Not a directory: '.DS_Store'?

新手上路,请多包涵

我想将一些图片从一个目录复制到另一个目录,这是我的代码:

 import os.path
import shutil

def copyFile(sourceDir,targetDir):
    for files in os.listdir(sourceDir):
        sourceFile=os.path.join(sourceDir,files)
        if os.path.isfile(sourceFile) and sourceFile.find('.jpg')>0:
            shutil.copy(sourceFile,targetDir)

for i in os.listdir('/Users/liuchong/Desktop/LFW/new'):

    copyFile(i,'/Users/liuchong/Desktop/LFW/lfw')

但是当我运行它时,终端告诉我 OSError: [Errno 20] Not a directory: '.DS_Store' 我知道“DS_dstore”是 Mac 中的一个隐藏文件,但我该如何解决这个错误?

原文由 Liu Chong 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.7k
2 个回答

你的逻辑似乎被严重破坏了。您遍历目录中的所有文件,将每个文件传递给 copyFile 。但是 该函数内部,您再次尝试遍历传递给该函数的“目录”中的每个文件:除了您不只将目录传递给该函数之外,您传递的是在原始目录中找到的每个文件。

目前尚不清楚您要做什么,但我认为您需要删除其中一个对 listdir 的调用以及相关的循环。

原文由 Daniel Roseman 发布,翻译遵循 CC BY-SA 3.0 许可协议

值得一提的是“不是目录”错误(Errno 20)的一般含义。这意味着您正在尝试使用子路径是真实文件而不是目录的路径进行操作。也就是说,它是一个格式错误的、不正确的路径。

示例:file.txt/test.txt 其中 file.txt 是现有的真实文件(不是目录)。

对于此类文件的每个 I/O 操作,Python 都会返回此错误:

 $ python -c 'import os; os.path.getsize("file.txt/test.txt");'
Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "/usr/lib/python2.7/genericpath.py", line 57, in getsize
    return os.stat(filename).st_size
OSError: [Errno 20] Not a directory: 'file.txt/test.txt'

操作系统也会返回此错误:

 $ stat file.txt/test.txt
stat: cannot stat 'file.txt/test.txt': Not a directory

每次出现此错误时,都意味着您在程序中的某处连接了文件+文件。

此错误是特定于 Unix 操作系统的。在 Windows 上,对于这种格式错误的路径,您应该得到“找不到文件”。

原文由 Alexander Samoylov 发布,翻译遵循 CC BY-SA 4.0 许可协议

推荐问题