在使用Python写入文件文件的过程中,需要判断文件夹路径是否存在,不存在需要创建多级路径

import os

#先定义一个带路径的文件
filename = "/home/mydir/test.txt"

#将文件路径分割出来
file_dir = os.path.split(filename )[0]

#判断文件路径是否存在,如果不存在,则创建,此处是创建多级目录
if not os.path.isdir(file_dir):
    os.makedirs(file_dir)

#然后再判断文件是否存在,如果不存在,则创建
if not os.path.exists(filename):
    os.system(r'touch %s' % filename)
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15