我正在构建一个基本文件服务器,我的程序找不到文件.
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)
Run Code Online (Sandbox Code Playgroud)
即使'myfile'和'path'正确[文件与服务器程序位于同一目录],它们总是返回False.
IDLE工作正常,但没有传递给函数.
>>> print os.path.exists("/user/server/foo.txt")
True
Run Code Online (Sandbox Code Playgroud)
我错过了什么?
[编辑:]输出:
Serving file: foo.txt
File exists?: False
Serving file: /user/server/foo.txt
File exists?: False
Run Code Online (Sandbox Code Playgroud)
Tha*_*all 18
在检查路径是否存在之前,我几乎100%确定您没有清理输入.这是我在翻译中运行的东西:
>>> from os.path import exists
>>> exists('dog.png')
True
>>> exists('dog.png\n')
False
Run Code Online (Sandbox Code Playgroud)
path
在检查是否存在空白之前尝试剥离空白.
如果您阅读os.path.exists()的 Python 文档,它会说存在文件或文件夹存在但os.path.exists()返回 false 的特定情况:
如果路径引用现有路径或打开的文件描述符,则返回 True。对于损坏的符号链接,返回 False。在某些平台上,如果未授予对请求的文件执行 os.stat() 的权限,即使该路径实际存在,此函数也可能返回 False。
没有直接回答这里提到的问题,但是当 os.path.exists() 一直给我“False”时,我发现了这个话题,即使在使用了 strip() 或 os.path.join() 之后。就我而言,我使用 ~ (tylda) 指向主目录,如下所示:
fileName = "~/path/to/file.txt"
Run Code Online (Sandbox Code Playgroud)
解决此问题的最佳方法是使用os.path.expanduser(fileName),然后检查文件是否存在。或者使用 os.path.abspath() 恢复绝对路径,然后从路径中删除“~”(但此解决方案不适用于所有场景)。
os.path.exists(os.path.abspath(fileName).replace("~",""))
Run Code Online (Sandbox Code Playgroud)
也许这对某人有帮助。