如何从列表中makedirs并包含python中的子目录列表?

时间:2016-06-04 15:53:51

标签: python

使用以下方法从列表中创建目录:

    require('sinon-as-promised');
    import request from 'supertest';

    const user = {
        username: newUserName,
        password: 'password'
    };


    factory.build('user', user,  function(err, userDocument) {
        UserMock.
            expects('findOne').withArgs(sinon.match.any)
            .chain('lean')
            .chain('exec')
            .yields( null, undefined);

        const docMock = sinon.mock(userDocument);
        docMock.expects('save')
        .resolves([]);

        request(app)
        .post('/userCreate')
        .send({username: newUserName, password: 'password')
        .expect(200)
        .end((err, res) => {
            if(err) done(err);
            should.not.exist(err);
            should.equal(res.body.success, true);
            done();
        });
});

还要在每个文件中添加三个子目录,例如[' sub1',' sub2',' sub3']

尝试过这样的事情(以及其他简单的方法)但没有成功:

import os

cwd = os.getcwd()
folders = ['file1','file2','file3']
for folder in folders:
    os.mkdir(os.path.join(cwd,folder))

有什么想法吗?谢谢!

2 个答案:

答案 0 :(得分:2)

import os

cwd = os.getcwd()
folders = ['file1','file2','file3']
subfolders = ['sub1','sub2','sub3']

for folder in folders:
    os.mkdir(os.path.join(cwd, folder))

    # Create sub-folders.
    for sub in subfolders:
        os.mkdir(os.path.join(cwd, folder, sub))

答案 1 :(得分:0)

无需显式创建父目录,因为makedirs自动创建父文件夹(如果不存在)。对于您的解决方案,一个可行的简明代码片段如下:

import os

cwd = os.getcwd();
folders = ['file1','file2','file3']
subfolders = ['sub1','sub2','sub3']

paths = [os.path.join(cwd, folder, sub) for folder in folders for sub in subfolders]

for path in paths:
    os.makedirs(path)

请注意,上面的代码只是对您第二次尝试的代码的一点修改:

import os

cwd = os.getcwd()
folders = ['file1','file2','file3']
subfolders = ['sub1','sub2','sub3']
for folder in folders:
    os.makedirs('os.path.join(cwd,folder/subfolders/)')