且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在Python 2.7中高效且优雅地创建目录和子目录?

更新时间:2023-11-27 23:30:34

Python遵循哲学

Python follows the philosophy

请求宽恕比请求允许更好.

It is better to ask for forgiveness than to ask for permission.

因此,无需检查isdir,您只需捕获如果叶子目录已存在就抛出的异常:

So rather than checking isdir, you would simply catch the exception thrown if the leaf directory already exists:

def Test():
    main_dir = ["FolderA", "FolderB"] 
    common_dir = ["SubFolder1", "SubFolder2", "SubFolder3"]

    for dir1 in main_dir:
        for dir2 in common_dir:
            try: os.makedirs(os.path.join(dir1,dir2))
            except OSError: pass

您还可以将字符串插值"%s/%s" %(dir1,dir2)替换为os.path.join(dir1, dir2)

You can also replace string interpolation "%s/%s" %(dir1,dir2) with os.path.join(dir1, dir2)

另一种更简洁的方法是执行笛卡尔积,而不是使用两个嵌套的for循环:

Another more succinct way is to do the cartesian product instead of using two nested for-loops:

for dir1, dir2 in itertools.product(main_dir, common_dir):
    try: os.makedirs(os.path.join(dir1,dir2))
    except OSError: pass