2024-03-29 10:19:11 发布
网友
如果不使用^{}语句,如何查看文件是否存在?
如果您检查的原因是为了执行类似if file_exists: open_it()的操作,则在尝试打开它时使用try会更安全。检查然后打开可能会导致文件被删除或移动,或者在您检查文件和尝试打开文件之间发生某些情况。
if file_exists: open_it()
try
如果不打算立即打开文件,可以使用^{}
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.
True
import os.path os.path.isfile(fname)
如果你需要确定它是一个文件。
从Python 3.4开始,^{} module提供了一种面向对象的方法(在Python 2.7中被移植到pathlib2):
pathlib2
from pathlib import Path my_file = Path("/path/to/file") if my_file.is_file(): # file exists
要检查目录,请执行以下操作:
if my_file.is_dir(): # directory exists
要检查Path对象是否独立于文件或目录而存在,请使用exists():
Path
exists()
if my_file.exists(): # path exists
也可以在try块中使用resolve(strict=True):
resolve(strict=True)
try: my_abs_path = my_file.resolve(strict=True) except FileNotFoundError: # doesn't exist else: # exists
与^{}不同,^{}将返回目录的True。 因此,根据您是否只需要普通文件或目录,您将使用isfile()或exists()。这是一个简单的REPL输出。
isfile()
>>> print os.path.isfile("/etc/password.txt") True >>> print os.path.isfile("/etc") False >>> print os.path.isfile("/does/not/exist") False >>> print os.path.exists("/etc/password.txt") True >>> print os.path.exists("/etc") True >>> print os.path.exists("/does/not/exist") False
您有^{}函数:
import os.path os.path.exists(file_path)
这将返回文件和目录的True,但是您可以使用
os.path.isfile(file_path)
测试它是否是一个特定的文件。它遵循符号链接。
如果您检查的原因是为了执行类似
if file_exists: open_it()
的操作,则在尝试打开它时使用try
会更安全。检查然后打开可能会导致文件被删除或移动,或者在您检查文件和尝试打开文件之间发生某些情况。如果不打算立即打开文件,可以使用^{}
如果你需要确定它是一个文件。
从Python 3.4开始,^{} module 提供了一种面向对象的方法(在Python 2.7中被移植到
pathlib2
):要检查目录,请执行以下操作:
要检查
Path
对象是否独立于文件或目录而存在,请使用exists()
:也可以在
try
块中使用resolve(strict=True)
:与^{} 不同,^{} 将返回目录的
True
。因此,根据您是否只需要普通文件或目录,您将使用
isfile()
或exists()
。这是一个简单的REPL输出。您有^{} 函数:
这将返回文件和目录的
True
,但是您可以使用测试它是否是一个特定的文件。它遵循符号链接。
相关问题 更多 >
编程相关推荐