无名阁,只为技术而生。流水不争先,争的是滔滔不绝。

python文件是否存在 文件夹是否存在 如何判断,方法总结与分享1(图文详解)

Python Micheal 9个月前 (12-04) 185次浏览 已收录 0个评论 扫描二维码
python文件是否存在 文件夹是否存在 如何判断,方法总结与分享1(图文详解)
python

python文件是否存在 文件夹是否存在 如何判断,方法总结与分享

Python检查文件或目录是否存在

在本教程中,我们将学习如何使用Python检查文件(或目录)是否存在。 为了检查这一点,我们使用python的内置函数,可以使用4种方法来验证文件或目录的存在,如下所示:

os.path.exists()
os.path.isfile()
os.path.isdir()
pathlibPath.exists()

os.path.exists()

使用path.exists()方法,可以快速检查文件或目录是否存在,

步骤1)在运行代码之前,导入os.path模块:

import os.path
from os import path

步骤2)使用path.exists()检查文件是否存在。

path.exists("guru99.txt")

步骤3)以下是完整代码

import os.path
from os import path

def main():

   print ("File exists:"+str(path.exists('guru99.txt')))
   print ("File exists:" + str(path.exists('career.guru99.txt')))
   print ("directory exists:" + str(path.exists('myDirectory')))

if __name__== "__main__":
   main()

方便测试,我们仅在工作目录中创建文件guru99.txt


输出:

File exists: True
File exists: False
directory exists: False

os.path.isfile()

我们可以使用isfile()方法来检查给定的输入是文件还是目录,代码如下:

import os.path
from os import path

def main():

	print ("Is it File?" + str(path.isfile('guru99.txt')))
	print ("Is it File?" + str(path.isfile('myDirectory')))
if __name__== "__main__":
	main()

输出:

Is it File? True
Is it File? False

os.path.isdir()

如果要确认给定路径指向目录,可以使用os.path.dir()函数,代码如下:

import os.path
from os import path

def main():

   print ("Is it Directory?" + str(path.isdir('guru99.txt')))
   print ("Is it Directory?" + str(path.isdir('myDirectory')))

if __name__== "__main__":
   main()

输出:

Is it Directory? False
Is it Directory? True

适用于Python 3.4的pathlibPath.exists()

Python 3.4及更高版本具有pathlib模块,用于处理文件系统路径。 它使用面向对象的方法来检查文件是否存在,代码如下:

import pathlib
file = pathlib.Path("guru99.txt")
if file.exists ():
    print ("File exist")
else:
    print ("File not exist")

输出:

File exist

以下是完整的代码:

import os
from os import path

def main():
  
    print(os.name)

print("Item exists:" + str(path.exists("guru99.txt")))
print("Item is a file: " + str(path.isfile("guru99.txt")))
print("Item is a directory: " + str(path.isdir("guru99.txt")))

if __name__ == "__main__":
    main()

输出:

Item exists: True
Item is a file: True
Item is a directory: False

总结:

如何检查文件是否存在


  1. os.path.exists()–如果路径或目录存在,则返回True。
  2. os.path.isfile()–如果路径为File,则返回True。
  3. os.path.isdir()-如果路径是Directory,则返回True。
  4. pathlib.Path.exists()-如果路径或目录存在,则返回True。 (要求在Python 3.4及更高版本中应用)

python数据分析 pandas遍历循环方法总结(图文详解1)

喜欢 (0)
[]
分享 (0)
关于作者:
流水不争先,争的是滔滔不绝
发表我的评论
取消评论

评论审核已启用。您的评论可能需要一段时间后才能被显示。

表情 贴图 加粗 删除线 居中 斜体 签到