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)
声明:该文观点仅代表作者本人,牛骨文系教育信息发布平台,牛骨文仅提供信息存储空间服务。