If the reason you're checking is so you can do something like if file_exists: open_it()
, it's safer to use a try
around the attempt to open it. Checking and then opening risks the file being deleted or moved or something between when you check and when you try to open it.
If you're not planning to open the file immediately, you can use os.path.isfile
Return
True
if path is an existing regular file. This follows symbolic links, so both islink() and isfile() can be true for the same path.
import os.path
os.path.isfile(fname)
if you need to be sure it's a file.
Starting with Python 3.4, the pathlib
module offers an object-oriented approach (backported to pathlib2
in Python 2.7):
from pathlib import Path
my_file = Path("/path/to/file")
if my_file.is_file():
# file exists
To check a directory, do:
if my_file.is_dir():
# directory exists
To check whether a Path
object exists independently of whether is it a file or directory, use exists()
:
if my_file.exists():
# path exists
You can also use resolve(strict=True)
in a try
block:
try:
my_abs_path = my_file.resolve(strict=True)
except FileNotFoundError:
# doesn't exist
else:
# exists
所以最好在做任何操作之前,先判断文件是否存在。 这里将介绍三种判断文件或文件夹是否存在的方法,分别使用 os模块 、 Try语句 、 pathlib ...
1) Using os.path.exists() function to check if a file exists ... To check if a file exists, you pass the file path to the exists() function from the os.path ...
2018年11月28日 ... 注意:这里的path是文件所处的路径,注意后缀名也是需要加上的。 1.2 具体使用. import os os.path.isfile('./file.txt ...
Python 操作文件时,我们一般要先判断指定的文件或目录是否存在,不然容易产生异常。 例如我们可以使用os 模块的os.path.exists() 方法来检测文件是否存在: import ...
Check file (arguable: also folder ("special" file) ?) existence; Don't use try / except / else / finally blocks. Possible solutions: [Python 3]: os.path.
2017年9月3日 ... 这里将介绍三种判断文件或文件夹是否存在的方法,分别使用os模块、Try语句、pathlib模块。1.使用os模块os模块中的os.path.exists()方法用于检验文件 ...
2018年10月18日 ... 1.使用os模块用os模块中os.path.exists()方法检测是否存在test_file.txt文件import osos.path.exists(test_fil...
2020年7月11日 ... Python检查文件或目录是否存在在本教程中,我们将学习如何使用Python检查 ... 如果要确认给定路径指向目录,可以使用os.path.dir()函数,代码如下:.
os.path.exists(path) - Returns true if the path is a file, directory, or a valid symlink.
Example. Check if file exists, then delete it: import os if os.path.exists("demofile.txt"): os.remove("demofile.txt") else: print("The file does not exist") ...
Python Check if Files Exist – os.path, Pathlib, try/except ... A simple way of checking if a file exists is by using the exists() function from the os ...