如何在Python 2.7中高效且优雅地创建目录和子目录? [英] How to create directories and sub directories efficiently and elegantly in Python 2.7?

查看:147
本文介绍了如何在Python 2.7中高效且优雅地创建目录和子目录?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在PC上的特定位置创建一堆目录和子目录.我的过程是这样的:

I am trying to create a bunch of directories and sub directories at a specific location in my PC. My process is something like this:

  1. 检查是否有任何具有相同目录名称的目录.如果是,则跳过.
  2. 如果没有,请创建目录以及该目录下的预定义子目录.

这是我使用os模块想到的代码:

This is the code I came up with using os module:

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

    for dir1 in main_dir:
        if not os.path.isdir(dir1):
            for dir2 in common_dir:
                os.makedirs("%s/%s" %(dir1,dir2))

我想知道是否有更好的方法来完成相同的任务(可能更短,更有效,更pythonic)?

I am wondering if there's any better way to do this very same task (probably shorter, more efficient and more pythonic)?

推荐答案

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

这篇关于如何在Python 2.7中高效且优雅地创建目录和子目录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆