Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/file/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 2.7 Python path.exists()返回False_Python 2.7_File - Fatal编程技术网

Python 2.7 Python path.exists()返回False

Python 2.7 Python path.exists()返回False,python-2.7,file,Python 2.7,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 e

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

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

这可能无法直接回答您的问题,但您可以使用“try/except”方法:
如果文件不存在(特别是如果它是一个内置函数),则使用该文件的任何函数都应该返回一个异常,并且您可以相应地执行操作。那么您就不需要自己检查文件是否存在。危险的也许吧,但这取决于您实际要做什么。

我几乎100%确定您在检查路径是否存在之前没有对输入进行清理。下面是我在我的解释器中运行的内容:

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

在检查路径是否存在之前,请尝试剥离路径上的空白。

如果您阅读的Python文档,它会指出存在文件或文件夹但返回false的特定情况:

如果路径引用现有路径或打开的文件,则返回True 描述符。对于断开的符号链接,返回False。在一些 如果未授予权限,则此函数可能返回False 在请求的文件上执行os.stat(),即使路径 物理存在

如中所说 这主要发生在空白处

我也面临这个问题。我花了很多时间才弄明白

python有一个名为
strip()
的函数,它删除了空格

如果变量
path\u to\u file
包含实际文件的路径,请尝试使用

如果path.exists(path\u to\u file.strip())
打印(“文件存在”)
其他:
打印(“文件不存在”)

这对我来说很有效。

没有直接回答这里提到的问题,但当os.path.exists()不断给我“False”时,我发现了这个主题,即使在使用strip()或os.path.join()之后也是如此。在我的例子中,我使用~(tylda)指向主目录,如下所示:

fileName = "~/path/to/file.txt"
修复此问题的最佳方法是使用os.path.expanduser(文件名),然后检查文件是否存在。或者,使用os.path.abspath()还原绝对路径,然后从路径中删除“~”(但此解决方案不适用于所有情况)


也许这会对某些人有所帮助。

如果由于空格而失败,这应该被视为一个bug

我发现,在某些情况下,结果是虚假的,这在某种程度上取决于文件服务器的状态。这种情况并非总是发生,只是偶尔发生一次

我发现只要至少延迟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)

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

即使在Windows上使用操作系统的本机目录分隔符“\”或“/”,在任何情况下都使用正斜杠对我来说都很好。操作系统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)



我想使用ubuntu上
下载
文件夹中的文件,但是
os.path.exists
无法使用绝对路径
~/Downloads/filename.txt


然后我使用
os.path.abspath(“”)
获取根路径
/home/yourpname/
并替换
~
,它可以工作

你能给我们这些打印语句的完整输出吗?什么是
myfile
<代码>/user/server/foo.txt?1。为什么要编写基本文件服务器?那么...怎么样2.myfile是否作为绝对路径传递?3.尝试导入pdb;pdb.在函数中设置_trace()并检查本地范围。路径的末尾是否有换行符?在将路径传递给
os.path.exists
之前,请尝试剥离路径上的空白。我刚刚观察到同样的情况。。。相同的文件名,没有更改,但经过数小时的操作后不存在伪文件。我使用一个文件的存在来保持一个线程的活动状态,所以它大约每30秒检查一次。这几乎就像平台中的某些东西由于高负载问题或访问争用而超时一样。读了你的评论后,我将增加我再次检查的延迟。
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)