Python 3.5 - 在 Windows 下创建带子文件夹的文件夹

标签 python windows path

是否有一些优雅的方法来创建如下所示的 Windows 路径。

home_dir = ('C:\First\Second\Third')        
if not os.path.exists(home_dir):
    os.mkdir(home_dir)
    print("Home directory %s was created." %home_dir)

我可以一步创建“C:\First”然后“Second”等等...

通过这段代码我得到:

FileNotFoundError: [WinError 3] The system cannot find the path specified: 'C:\First\Second\Third'

最佳答案

您应该使用 os.path.isdir 检查目录路径是否存在:

Return True if path is an existing directory.

os.path.isdir("C:\First\Second\Third")

这将避免 FileNotFoundError。

然后创建目录。看起来像这样:

home_dir = ('C:\First\Second\Third')        
if not os.path.isdir(home_dir):
    os.makedirs(home_dir)
    print("Home directory %s was created." %home_dir)

关于Python 3.5 - 在 Windows 下创建带子文件夹的文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35598020/

相关文章:

c# - 在 C# 中更改 Windows 的书写语言

cocoa - 解析 NSURL 中的所有符号链接(symbolic link)

MySQL - 使用可变路径加载数据文件

python - 在 pandas 的数据框中用 NaN 替换所有值

python - 在python numpy中查找特定值之前最后一个元素的位置

python - 几何形状Python之间的测地距离

Java 拆分路径..?

python - cmap 到 Matplotlib 中的 rgba

c++ - 如何在Windows C++中像S-1-5-21-123697389-1196883430-1112475604-1016这样创建SID

windows - PE/COFF 文件扩展