os.path.exists()函数怎么在python中使用

发布时间:2021-03-15 17:09:46 作者:Leah
来源:亿速云 阅读:1343

本篇文章给大家分享的是有关os.path.exists()函数怎么在python中使用,小编觉得挺实用的,因此分享给大家学习,希望大家阅读完这篇文章后可以有所收获,话不多说,跟着小编一起来看看吧。

os即operating system(操作系统),Python 的 os 模块封装了常见的文件和目录操作。

os.path模块主要用于文件的属性获取,exists是“存在”的意思,所以顾名思义,os.path.exists()就是判断括号里的文件是否存在的意思,括号内的可以是文件路径。

举个栗子:

user.py为存在于当前目录的一个文件

输入代码:

import os
path = os.path.exists('user.py')
print(path)

输出结果:

True
 
Process finished with exit code 0

如果不存在,返回的则是FALSE。

补充:

Python中os.path和os.makedirs的运用

判断文件或文件夹是否存在,创建文件夹

import os
import numpy as np
 
data = np.array([1, 2, 3])
if not os.path.exists("./data/"):
 print("# path not exists")
 os.makedirs("./data/")
 if not os.path.exists("./data/data.npy"):
  print("# data.npy not exists")
  np.save("./data/data.npy", data)
 
print("# path exists? :", os.path.exists("./data/"))
print("# data.npy exists? :", os.path.exists("./data/data.npy"))

运行结果:

# path not exists
# data.npy not exists
# path exists? : True
# data.npy exists? : True

以上就是os.path.exists()函数怎么在python中使用,小编相信有部分知识点可能是我们日常工作会见到或用到的。希望你能通过这篇文章学到更多知识。更多详情敬请关注亿速云行业资讯频道。

推荐阅读:
  1. Python主要工作岗位有哪些 如何快速学会Python
  2. python中 or 和 | 有什么区别

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

python os.path.exists()

上一篇:怎么在python中使用sqlite3判断cursor的结果是否为空

下一篇:怎么在mysql中根据索引优化查询速度

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》