簡體   English   中英

如何從 Python 中的多個文件夾中提取文件

[英]How to extract files from across multiple folders in Python

本質上...我在本地驅動器上有 27 個文件夾,每個文件夾包含數萬個.jpg。 我已經生成了一個包含 5,000 個這些圖像的隨機列表,分布在 27 個文件夾中,我希望將它們轉移到一個文件夾中。

我有我需要的所有 5,000 個文件名的 a.csv 列表,並且想知道將這些全部放入一個文件夾的最簡單方法是什么?

我看到很多在線資源解釋了如何使用“glob.glob”和“os.walk”方法來提取具有特定文件擴展名(例如 .txt)的所有文件,但是我需要根據特定文件名提取它們我在一個列表中。

我通常在 Python 工作,但是如果沒有我缺少的另一種明顯的非編碼方式,請也建議這樣做。

謝謝, R

這是一個相對基本的 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 -bash 目錄

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM