【问题标题】:python create recursive folder structurepython创建递归文件夹结构
【发布时间】:2015-03-03 17:27:29
【问题描述】:

我正在编写一个脚本来自动创建测试文件/文件夹结构 - 另一个脚本的输入(根据文件列表仅移动一些文件)。我下面的代码有效,但是有没有更 Pythonic 的方式来完成相同的任务?

import os
import shutil

os.chdir('c:/')
if not os.path.exists('c:/pythontest'):
    os.mkdir('c:/pythontest')
else:
    shutil.rmtree('c:/pythontest')
    os.mkdir('c:\pythontest')

os.chdir('c:/pythontest')

for i in range(0,3):
    os.mkdir('folder%d' % i)
    fileName = 'folder%d' % i
    filePath = os.path.join(os.curdir, fileName)
    print filePath
    os.chdir(filePath)
    for j in range(0,3):
        os.mkdir('folder%d_%d' % (i,j))
        fileName = 'folder%d_%d' % (i,j)
        filePath = os.path.join(os.curdir, fileName)
        print str(filePath)
        os.chdir(filePath)
        for k in range(0,3):
            try:
                f = open('file%d_%d_%d.txt' % (i,j,k), 'w')
            except IOError:
                pass
        os.chdir('..')
    os.chdir('..')

【问题讨论】:

    标签: python operating-system shutil


    【解决方案1】:

    我只能建议一些小的样式改进 - 并在一个函数中移动所有内容,这样可以加快速度。例如:

    import os
    import shutil
    
    def doit():
        shutil.rmtree('c:/pythontest', ignore_errors=True)
        os.mkdir('c:/pythontest')
        os.chdir('c:/pythontest')
    
        for i in range(0,3):
            fileName = 'folder%d' % i
            print fileName
            os.mkdir(fileName)
            os.chdir(fileName)
            for j in range(0,3):
                fileName = 'folder%d_%d' % (i,j)
                print fileName
                os.mkdir(fileName)
                os.chdir(fileName)
                for k in range(0,3):
                    try:
                        with open('file%d_%d_%d.txt' % (i,j,k), 'w'):
                            pass
                    except IOError:
                        pass
                os.chdir('..')
            os.chdir('..')
    

    次要但累积的改进包括避免重复和避免冗余(例如在文件名前添加“./”以生成完全相同的文件路径)。

    【讨论】: