Python path.exists()返回False

时间:2012-09-26 20:14:12

标签: python file

我正在构建一个基本的文件服务器,我的程序找不到文件。

def sendfile(sock, myfile):
    print 'Serving file:', myfile
    print 'File exists?:', os.path.exists(myfile)

    path = os.path.normpath(os.path.join(os.getcwd(), myfile))
    print 'Serving file:', path
    print 'File exists?:', os.path.exists(path)

即使'myfile'和'path'正确[文件与服务器程序在同一目录中],它们也始终返回False。

IDLE工作正常,但没有传递给函数。

>>> print os.path.exists("/user/server/foo.txt")  
True

我错过了什么?

[编辑:]输出:

Serving file: foo.txt

File exists?: False
Serving file: /user/server/foo.txt

File exists?: False

8 个答案:

答案 0 :(得分:17)

在检查路径是否存在之前,我几乎100%确定您没有清理输入。这是我在翻译中运行的东西:

>>> from os.path import exists
>>> exists('dog.png')
True
>>> exists('dog.png\n')
False

尝试在path上删除空格,然后再检查它是否存在。

答案 1 :(得分:2)

这可能无法直接回答您的问题,但您可以使用“try / except”方法: 如果文件不存在,任何函数使用该文件都应该返回异常(特别是如果它是内置函数),并且您可以采取相应的行动。然后您无需检查文件是否存在。危险吗?也许,但这取决于你实际上要做的事情。

答案 2 :(得分:2)

如果您阅读了os.path.exists()的Python文档,它会说存在文件或文件夹但os.path.exists()返回false的特定情况:

  

如果path指的是现有路径或打开文件,则返回True   描述。对于损坏的符号链接,返回False。一些   平台,如果未授予权限,此函数可能返回False   在请求的文件上执行os.stat(),即使是路径   身体存在。

答案 3 :(得分:2)

没有直接回答这里提到的问题,但是当os.path.exists()一直给我“ False”时,即使在使用strip()或os.path.join()之后,我也找到了这个主题。就我而言,我使用〜(tylda)指向主目录,如下所示:

fileName = "~/path/to/file.txt"

解决此问题的最佳方法是使用 os.path.expanduser(fileName),然后检查文件是否存在。或者,使用os.path.abspath()恢复绝对路径,然后从路径中删除“〜”(但是此解决方案并非在所有情况下都适用)。

os.path.exists(os.path.abspath(fileName).replace("~",""))

也许这对某人会有帮助。

答案 4 :(得分:1)

this answer中所述 这主要发生在空白处。

我也遇到了这个问题。我花了很多时间来解决这个问题。

python有一个名为strip()的函数,用于删除空格。

如果变量path_to_file包含实际文件的路径,请尝试使用

if path.exists(path_to_file.strip())
        print("file exists")
else:
        print("file doesn't exist")

这对我有用。

答案 5 :(得分:0)

坦白地说,如果由于空格而失败,则应将其视为错误。

我发现在某些情况下,结果将是虚假的,具体取决于文件服务器的状态。这并非总是发生,只是偶尔出现。

我发现至少延迟10秒,我可以避免失败。 在这种情况下,我将反复打开zip归档文件以访问特定的压缩文件。在尝试打开它之前,它会检查路径是否存在(由于这个奇怪的问题,请尝试在此路径下使用)。如果失败,则会以增加的延迟循环等待。我发现通常会发现文件经过4个循环(延迟10秒)后再次存在,因此结束了。

这是我的循环打印语句的输出:

Archive r:\ballotimagearchive\ca_san_francisco_2020_pri\d03.zip does not exist according to os.path.exists().
Waiting 1 seconds
Waiting 2 seconds
Waiting 3 seconds
Waiting 4 seconds
After wait of 10 secs, r:\ballotimagearchive\ca_san_francisco_2020_pri\d03.zip now exists according to os.path.exists().

以及产生此代码的代码段。

    if os.path.isfile(source_path):
    print(f"Verified that {source_path} exists.")
else:
    print(f"Archive {source_path} does not exist according to os.path.exists().")

    # this may be a spurious problem related to using a file server.

    tot_time = 0
    for i in range(1,20):
        print(f"Waiting {i} seconds")
        time.sleep(i)
        tot_time += i 
        if os.path.isfile(source_path):
            print(f"After wait of {tot_time} secs, {source_path} now exists according to os.path.exists().")
            break
    else:
        print(f"After wait of {tot_time} secs, {source_path} still not found according to os.path.exists().")
        sys.exit(1)

答案 6 :(得分:0)

我遇到了同样的问题,并找到了以下解决方案:

甚至在Windows上也使用OS的本机目录分隔符'\'或'/',在所有情况下都使用正斜杠对我来说很好。 os.sep可以帮助您。

除此之外,清理路径字符串有点类似于此:

import re
from os import path
strPath = "c:/dir1/dir2/dir3/dir4/important-file.ext"
strPath = re.escape(strPath)

bTest = os.access(strPath, os.F_OK)

# or the classic
bTest = path.exists(strPath)
print(bTest)


答案 7 :(得分:0)

我想使用ubuntu上Downloads文件夹中的文件,但是os.path.exists找不到使用绝对路径~/Downloads/filename.txt的文件。

然后,我使用os.path.abspath('')获取根路径/home/yourPCname/并替换~,就可以了!