带有父目录和exist_ok的Python mkdir没有创建最终目录



代码在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.paparent.absolute((的调用有关,但如果我尝试使用os.path.dirname,我会得到同样的结果。对不起,如果这个已经回答了,我发现很多";如何创建目录";但没有涉及到这个问题。也很抱歉有任何格式问题-这是我第一次发布这个StackOverflow。

由于targetpath的每个值都已经是您要创建的每个目录的绝对路径,当您在其上调用os.path.dirname时,由于该路径没有以/结束,因此您可以将其上最后一个/(在您的情况下是内部目录(右侧的所有内容都剪切掉。

所以基本上你不需要在上面调用os.path.dirname,只需执行:

os.makedirs(targetpath, 0o755, True)

最新更新