加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python 判断目录和文件、文件夹 是否存在,若不存在即创建

发布时间:2020-12-20 10:12:49 所属栏目:Python 来源:网络整理
导读:判断目录是否存在 import os dirs = 'C:UsersAdministratorDesktopworkpython' if not os.path.exists(dirs): os.makedirs(dirs) 判断文件夹是否存在 import os path =os.path.dirname(os.getcwd())+ 'Screenshots' if not os.path.exists(path): os

判断目录是否存在
import os
dirs = 'C:UsersAdministratorDesktopworkpython'

if not os.path.exists(dirs):
os.makedirs(dirs)


判断文件夹是否存在

import os

path =os.path.dirname(os.getcwd())+ 'Screenshots'

if not os.path.exists(path):
os.makedirs(path)

?

判断文件是否存在
import os
filename ='C:UsersAdministratorDesktopworkpythonpoem.txt'

if not os.path.exists(filename):
os.system(r"touch {}".format(path))? #调用系统命令行来创建文件

?

os.getcwd() :获取的当前最外层调用的脚本路径,即getPath所在的目录也可描述为起始的执行目录,A调用B,起始的是A,那么获取的就是A所在的目录路径。 获取脚本路径所在的上层目录

os.path.dirname():去掉脚本的文件名,返回目录。返回脚本文件所在的目录路径

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读