8

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

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。请注意,我的代码仅将文件移动到它们的公共父目录,而不是任意目的地。

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

4

5 回答 5

9

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

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(iterator, 1, None)。另一种更明确的方法是这样做:

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)
于 2013-07-09T13:16:45.757 回答
4

这样做,如果文件发生冲突,它也会重命名文件(我注释掉了实际的移动并替换为副本):

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)
于 2013-07-09T12:04:16.207 回答
3

通过目录递归运行,移动文件并启动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))
于 2013-07-09T11:39:28.000 回答
1
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来源。如果它们发生冲突,则不更改文件名。

samefile是比较路径的安全方法。但它不适用于 Windows,因此请检查如何在 Windows 和 Python 2.7 上模拟 os.path.samefile 行为?.

于 2013-07-09T12:16:53.460 回答
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)
于 2021-02-10T18:29:15.147 回答