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

判断目录是否存在

import os
dirs = '/Users/joseph/work/python/'

if not os.path.exists(dirs):
    os.makedirs(dirs)
    
    
  • 1
  • 2
  • 3
  • 4
  • 5

判断文件是否存在

import os
filename = '/Users/joseph/work/python/poem.txt'

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

判断目录是否存在

import os
dirs = '/Users/joseph/work/python/'

if not os.path.exists(dirs):
    os.makedirs(dirs)
  
  
  • 1
  • 2
  • 3
  • 4
  • 5

判断文件是否存在

import os
filename = '/Users/joseph/work/python/poem.txt'

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

猜你喜欢

转载自blog.csdn.net/intjun/article/details/81702092