python3输入文件路径,若没有,则自动创建文件夹与文件名,并读写文件?

python3输入文件路径,若没有,则自动创建文件夹与文件名,并读写文件?

import os

fullpath = "D:\\data\\text\\Test\\test1.txt"
paths, file = [], None
path = fullpath[:]
while file!='':
    path,file = os.path.split(path)
    if file:
        paths.append(file)

while len(paths)>1:
    path += ('' if path[-1]=='\\' else '\\') + paths.pop()
    if not os.path.isdir(path):
        os.mkdir(path)

with open(fullpath, 'w') as f:
    f.write('test:测试内容!')

仅供参考

import os
path="./tmp/tmp.txt"
if os.path.exists(path)==False:
    mkpath=os.makedirs(os.path.dirname(path)) #创建目录
    with open(path,'w',encoding='utf-8') as f: #写文件
        f.write("hello")
else:
    with open(path, 'r',encoding='utf-8') as f: #读文件
        lines=f.readlines()
        for line in lines:
            print(line)