【问题标题】:How to extract files from across multiple folders in Python如何从 Python 中的多个文件夹中提取文件
【发布时间】:2020-11-30 12:14:34
【问题描述】:

基本上...我在本地驱动器上有 27 个文件夹,每个文件夹包含数万个 .jpg。我生成了一个包含 5,000 张图像的随机列表,分布在 27 个文件夹中,我希望将它们转移到一个文件夹中。

我有一个包含我需要的所有 5,000 个文件名的 .csv 列表,我想知道将这些文件名全部放入一个文件夹的最简单方法是什么?

我看到大量在线资源解释了如何使用“glob.glob”和“os.walk”方法来提取具有特定文件扩展名(例如 .txt)的所有文件,但是我需要根据我在列表中的特定文件名。

我通常在 Python 中工作,但如果我缺少另一种明显的非编码方式来实现这一点,请也提出建议。

谢谢,R

【问题讨论】:

    标签: python python-3.x csv glob os.walk


    【解决方案1】:

    这是一个相对基本的 Python 解决方案,但也许您可以将其调整为更有用的东西。

    import csv
    import os
    import shutil
    
    # Generator for all files in root_dir
    def list_files(my_root_dir):
        for path, _, files in os.walk(my_root_dir):
            yield path, files
    
    
    def copy_files(my_csv_file, my_root_dir, my_target_dir):
        with open(my_csv_file, "r") as csvfile:
            csv_reader = csv.reader(csvfile, delimiter=",")
            for line in csv_reader:
                for image in line:
                    for path, files in list_files(my_root_dir):
                        # Careful not to copy files already copied to target_dir
                        if image in files and path != my_target_dir:
                            shutil.copy(os.path.join(path, image), my_target_dir)
                            break
    

    如果你想坚持shell,这里有一些想法:https://unix.stackexchange.com/questions/402728/how-to-move-files-specified-in-a-text-file-to-another-directory-on-bash

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-10-09
      • 1970-01-01
      • 2023-02-05
      • 1970-01-01
      • 2020-11-20
      • 1970-01-01
      • 2019-06-21
      • 1970-01-01
      相关资源
      最近更新 更多