【问题标题】:Python mkdir with parent and exist_ok not creating final directory带有父级和exist_ok的Python mkdir不创建最终目录
【发布时间】:2021-08-09 23:12:56
【问题描述】:

代码循环访问 sqlite3 数据库中的数据并创建目录以提取信息;但是,永远不会创建最终目录。应该是 DCIM/dir1 DCIM/dir2 DCIM...

for row in rows:
        localfile = row[0]
        fileloc = row[1]
        # Skip empty entries
        if not localfile or not fileloc:
                continue
        # Get path location of file, create it, ignore if exists
        path = Path(fileloc)
        mkpath = path.parent.absolute()
        targetpath = os.path.join(os.path.join(os.environ.get("HOME"), mkpath))
        print(f"Creating {targetpath}")
        if not os.path.exists(targetpath):
                #Path(os.path.dirname(targetpath)).mkdir(parents=True, exist_ok=True)
                os.makedirs(os.path.dirname(targetpath), 0o755, True)

我确定这还不是最佳的,但真正的问题是创建了 $HOME/DCIM 但 $HOME/DCIM/dir1 等。打印语句显示正确的输出:

Creating /usr/home/jim/DCIM/dir1
Creating /usr/home/jim/DCIM/dir2
Creating /usr/home/jim/DCIM/dir3
Creating /usr/home/jim/DCIM/dir4

但是 DCIM 是空的。我认为父级可能正在覆盖,但是在使用 $HOME 尝试此操作并阅读文档之后,这没有任何意义。我觉得这与对 path.parent.absolute() 的调用有关,但如果我尝试使用 os.path.dirname,我会得到相同的结果。抱歉,如果已经回答了这个问题,我发现了很多“如何创建目录”,但没有任何内容涵盖这个问题。对于任何格式问题也很抱歉 - 这是我在 StackOverflow 上的第一篇文章。

【问题讨论】:

  • 尝试将 os.path.dirname(targetpath) 更改为 targetpath
  • 正确,谢谢!既然您的解决方案效果很好,我该如何将此标记为已回答!

标签: python mkdir


【解决方案1】:

由于targetpath的每个值已经是你要创建的每个目录的绝对路径,当你在上面调用os.path.dirname时,由于路径不以/结尾,你把所有的都切到右边最后一个/ (在你的情况下是内部目录)。

所以基本上你不需要打电话给os.path.dirname,只需这样做:

os.makedirs(targetpath, 0o755, True)

【讨论】:

    猜你喜欢
    • 2020-07-22
    • 1970-01-01
    • 2014-11-19
    • 1970-01-01
    • 2013-07-18
    • 2014-02-05
    • 1970-01-01
    • 2015-04-06
    相关资源
    最近更新 更多