如何在Python中检查文件是否存在?

7

@vpit3833:我会说“很有可能”。;-) - GaretJax
请注意,所选答案是不正确的 - 问题是关于文件的,所选答案也会对目录回答“是”。 - reducing activity
3个回答

13

使用os模块非常容易。

from os.path import exists
print exists("C:\somefile.txt")

如果文件位于“扩展”路径中怎么办?例如“\?\C:<very long path>”。 - bgura
@bgura 为什么会有所不同呢? - Benj
@Benj。我之前在Windows上遇到了长路径的问题,Python一直说路径不存在。在Windows上,您需要使用特殊语法来访问“长”路径,请参见此链接:https://dev59.com/R2Ei5IYBdhLWcg3whcri#21194605。我无法立即回想起Python是否支持该语法,或者它是否会通过传统格式(即C:\ path \ ...)规范化长路径。 - bgura
@bgura 这很有趣!但我恐怕无法回答你的问题... - Benj
这是一个不正确的答案 - 问题是关于文件的,这个答案也会对目录回答“是”。 - reducing activity

5

查阅手册即可,这是一个非常简单的问题:

http://docs.python.org/library/os.path.html#os.path.exists

os.path.exists(path)

Return True if path refers to an existing path. Returns False for broken symbolic links. On some platforms, this function may return False if permission is not granted to execute os.stat() on the requested file, even if the path physically exists.


这是一个不正确的答案 - 问题是关于文件的,这个答案也会对目录回答“是”。 - reducing activity

4

你能否请简要概括一下这些链接? - Benj

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接