在Python中展平复杂的目录结构

时间:2013-07-09 11:37:15

标签: python directory-structure flatten file-move

我想将文件从复杂的目录结构移动到一个地方。例如,我有这种深层次的层次结构:

foo/
    foo2/
        1.jpg
    2.jpg
    ...

我希望它是:

1.jpg
2.jpg
...

我目前的解决方案:

def move(destination):
    for_removal = os.path.join(destination, '\\')
    is_in_parent = lambda x: x.find(for_removal) > -1
    with directory(destination):
        files_to_move = filter(is_in_parent,
                               glob_recursive(path='.'))
    for file in files_to_move:
        shutil.move(file, destination)

定义:directoryglob_recursive。请注意,我的代码只将文件移动到其公共父目录,而不是任意目标。

如何将所有文件从复杂的层次结构简洁而优雅地移动到一个地方?

5 个答案:

答案 0 :(得分:2)

这样做,它还会重命名文件,如果它们发生碰撞(我注释掉实际移动并替换为副本):

import os
import sys
import string
import shutil

#Generate the file paths to traverse, or a single path if a file name was given
def getfiles(path):
    if os.path.isdir(path):
        for root, dirs, files in os.walk(path):
            for name in files:
                yield os.path.join(root, name)
    else:
        yield path

destination = "./newdir/"
fromdir = "./test/"
for f in getfiles(fromdir):
    filename = string.split(f, '/')[-1]
    if os.path.isfile(destination+filename):
        filename = f.replace(fromdir,"",1).replace("/","_")
    #os.rename(f, destination+filename)
    shutil.copy(f, destination+filename)

答案 1 :(得分:1)

通过目录递归运行,移动文件并为目录启动move

import shutil
import os

def move(destination, depth=None):
    if not depth:
        depth = []
    for file_or_dir in os.listdir(os.path.join([destination] + depth, os.sep)):
        if os.path.isfile(file_or_dir):
            shutil.move(file_or_dir, destination)
        else:
            move(destination, os.path.join(depth + [file_or_dir], os.sep))

答案 2 :(得分:1)

我不喜欢测试要移动的文件的名称,看看我们是否已经在目标目录中。相反,此解决方案仅扫描目标

的子目录
import os
import itertools
import shutil


def move(destination):
    all_files = []
    for root, _dirs, files in itertools.islice(os.walk(destination), 1, None):
        for filename in files:
            all_files.append(os.path.join(root, filename))
    for filename in all_files:
        shutil.move(filename, destination)

说明:os.walk以“自上而下”的方式递归地遍历目的地。整个文件名是使用os.path.join(root,filename)调用构造的。现在,为了防止扫描目标顶部的文件,我们只需要忽略os.walk迭代的第一个元素。为此,我使用islice(迭代器,1,无)。另一种更明确的方法是:

def move(destination):
    all_files = []
    first_loop_pass = True
    for root, _dirs, files in os.walk(destination):
        if first_loop_pass:
            first_loop_pass = False
            continue
        for filename in files:
            all_files.append(os.path.join(root, filename))
    for filename in all_files:
        shutil.move(filename, destination)

答案 3 :(得分:0)

import os.path, shutil

def move(src, dest):
    not_in_dest = lambda x: os.path.samefile(x, dest)
    files_to_move = filter(not_in_dest,
                           glob_recursive(path=src))

    for f in files_to_move:
        shutil.move(f, dest)
glob_recursive的{​​p> Source。如果文件名冲突,则不会更改文件名。

samefile是比较路径的安全方式。但它在Windows上不起作用,因此请检查How to emulate os.path.samefile behaviour on Windows and Python 2.7?

答案 4 :(得分:0)

def splitPath(p):
    a,b = os.path.split(p)
    return (splitPath(a) if len(a) and len(b) else []) + [b]

def safeprint(s):
    try:
        print(s)
    except UnicodeEncodeError:
        if sys.version_info >= (3,):
            print(s.encode('utf8').decode(sys.stdout.encoding))
        else:
            print(s.encode('utf8'))

def flatten(root, doit):
    
    SEP  = "¦"
    REPL = "?"

    folderCount = 0
    fileCount = 0

    if not doit:
        print("Simulating:")

    for path, dirs, files in os.walk(root, topdown=False):

        if path != root:

            for f in files:

                sp = splitPath(path)

                np = ""

                for element in sp[1:]:
                    e2 = element.replace(SEP, REPL)
                    np += e2 + SEP

                f2 = f.replace(SEP, REPL)
                newName = np + f2

                safeprint("Moved:   "+ newName )
                if doit:
                    shutil.move(os.path.join(path, f), os.path.join(root, f))
                    # Uncomment, if you want filenames to be based on folder hierarchy.
                    #shutil.move(os.path.join(path, f), os.path.join(root, newName))
                fileCount += 1

            safeprint("Removed: "+ path)
            if doit:
                os.rmdir(path)
            folderCount += 1

    if doit:
        print("Done.")        
    else:
        print("Simulation complete.")


    print("Moved files:", fileCount)
    print("Removed folders:", folderCount)


directory_path = r"C:\Users\jd\Documents\myFtpData"
flatten(directory_path, True)