(python)os.path.exists 和 os.path.isfile 是不是不可信?

1 投票
2 回答
12296 浏览
提问于 2025-04-16 09:13

os.path.exists这个函数给我的结果不太对。

这不是下面链接讨论的同样问题,因为我是在Windows系统上。还有其他可能导致它出错的原因吗?

os.path.exists()不靠谱

当我测试一个和*.py脚本在同一个文件夹里的文件时,结果是正常的,但在它的子文件夹里就不行了。

-编辑-

我使用的是绝对路径。

我在这个脚本运行时查看其中一个子文件夹,能清楚地看到文件的最后修改时间在Windows资源管理器里被改变了。
我想不出还有其他什么东西会修改这些文件。

def SaveIfNewer(doc, aiFile, pngFile):
    options = win32com.client.Dispatch('Illustrator.ExportOptionsPNG24')
    options.SetArtBoardClipping(True)
    if (os.path.exists(pngFile)):
        aiFileTime = os.stat(aiFile)[8]
        pngFileTime = os.stat(pngFile)[8]
        print("aiFileTime: ", aiFileTime, "pngFileTime: ", pngFileTime)

        if(aiFileTime > pngFileTime):
            os.remove(pngFile)

    if( not os.path.isfile(pngFile)):
        doc.Export(pngFile, constants.aiPNG24, options)
        print 'exporting:', pngFile
    else:
        print 'skipping file:', pngFile

2 个回答

1

结果发现,os.path.exists 和 os.path.isfile 是区分大小写的。

真是的!

3

os.path.existsos.path.isfile 在Windows系统上是不区分大小写的。

这是我在Windows 7(Python 2.7)上得到的结果:

>>> os.path.exists('C:/.rnd')
True
>>> os.path.exists('C:/.RND')
True
>>> os.path.isfile('C:/.rnd')
True
>>> os.path.isfile('C:/.RND')
True

撰写回答