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


判断目录是否存在
import os
dirs = 'C:\Users\Administrator\Desktop\work\python\'

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:\Users\Administrator\Desktop\work\python\poem.txt'

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

 

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

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


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM