「已注销」 2022-06-24 18:48 采纳率: 98.1%
浏览 46
已结题

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

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

  • 写回答

2条回答 默认 最新

  • Hann Yang 优质创作者: 编程框架技术领域 2022-06-24 20:21
    关注
    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:测试内容!')
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

问题事件

  • 系统已结题 7月3日
  • 已采纳回答 6月25日
  • 创建了问题 6月24日