【问题标题】:python how to collect a specific file from a list of folders and savepython如何从文件夹列表中收集特定文件并保存
【发布时间】:2020-04-17 18:39:27
【问题描述】:

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

在每个文件夹中

我现在的代码:

import os
import glob 

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

这不起作用。

【问题讨论】:

  • 列表jpg_files 是否按预期提供了所有 jpg 文件?
  • 不同文件夹下的JPG文件可以同名吗?
  • @timgeb 不,他们有不同的名字。但是每个文件夹只有JPG 文件。所以,我相信,不用担心文件名。

标签: python file file-io


【解决方案1】:

要在树中查找图像,我会使用 os.walk。您可以在下面找到“查找和移动”功能的完整示例,该功能将所有文件移动到给定路径,并为重复的文件名创建新文件名。

简单的“查找和替换”功能还将使用功能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)

【讨论】:

  • 考虑使用os.path.splitext
  • 好主意。答案已调整。
  • @timgeb,我添加了一些检查。有关如何改进添加到文件名的索引的任何建议?
  • 我倾向于在这些情况下作弊,并在文件名前加上文件目录路径的 SHA-1 哈希 (hashlib.sha1(root.encode('utf-8')).digest().hex())。假设你可以接受每几百万年的文件名冲突:)
  • 我决定尝试使用正则表达式来解决文件索引问题。我相信这结束了这个问题。很高兴听到任何更多的调整,以使其成为更好的例子。
猜你喜欢
  • 1970-01-01
  • 2022-01-19
  • 1970-01-01
  • 1970-01-01
  • 2014-07-18
  • 2022-01-06
  • 1970-01-01
  • 1970-01-01
  • 2021-02-18
相关资源
最近更新 更多