python如何从文件夹列表中收集一个特定的文件并保存起来

问题描述 投票:1回答:1

我在一个主文件夹里有很多文件夹,如下所示。每个文件夹都包含一个.JPG文件。我想提取所有这些文件,并将它们存储在这个主文件夹中。

enter image description here

在每个文件夹中 enter image description here

我现在的代码。

import os
import glob 

os.chdir('Master folder')
extension = 'JPG'
jpg_files= [i for i in glob.glob('*.{}'.format(extension))]

这个没有用

python file file-io
1个回答
3
投票

为了找到树中的图片,我会使用os.walk.com。 下面你可以找到一个完整的 "查找和移动 "功能的例子,它可以将所有文件移动到你给定的路径上,并为重复的文件名创建一个新的文件名。

这个简单的 "查找和替换 "函数也会检查你所给的路径中的文件。add_index_to_filepath 无论文件是否已经存在,都要在路径上添加一个索引(n)。 例如:如果 image.jpg 会存在,就会把下一个变成变成。image (1).jpg 并将以下内容纳入其中 image (2).jpg 诸如此类。

import os
import re
import shutil

def add_index_to_filepath(path):
    '''
    Check if a file exists, and append '(n)' if true.
    '''
    # If the past exists, go adjust it
    if os.path.exists(path):
        # pull apart your path and filenames
        folder, file = os.path.split(path)
        filename, extension = os.path.splitext(file)

        # discover the current index, and correct filename
        try:
            regex = re.compile(r'\(([0-9]*)\)$')
            findex = regex.findall(filename)[0]
            filename = regex.sub('({})'.format(int(findex) + 1), filename)
        except IndexError:
            filename = filename + ' (1)'

        # Glue your path back together.
        new_path = os.path.join(folder, '{}{}'.format(filename, extension))

        # Recursivly call your function, go keep verifying if it exists.
        return add_index_to_filepath(new_path)

    return path


def find_and_move_files(path, extension_list):
    '''
    Walk through a given path and move the files from the sub-dir to the path.
    Upper-and lower-case are ignored.  Duplicates get a new filename.
    '''
    files_moved = []

    # First walk through the path, to list all files.
    for root, dirs, files in os.walk(path, topdown=False):
        for file in files:
            # Is your extension wanted?
            extension = os.path.splitext(file)[-1].lower()
            if extension in extension_list:
                # Perpare your old an new path, and move
                old_path = os.path.join(root, file)
                new_path = add_index_to_filepath(os.path.join(path, file))

                if new_path in files_moved:
                    shutil.move(old_path, new_path)

                # Lets keep track of what we moved to return it in the end
                files_moved.append(new_path)

    return files_moved

path = '.'  # your filepath for the  master-folder
extensions = ['.jpg', '.jpeg']  # There are some variations of a jpeg-file extension.
found_files = find_and_move_files(path, extensions)
© www.soinside.com 2019 - 2024. All rights reserved.