是否有一些优雅的方法来创建如下所示的 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/