【发布时间】: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 -
正确,谢谢!既然您的解决方案效果很好,我该如何将此标记为已回答!