.
├── input
│   └── _sampled
└── src
    └── random_sampling.py
random_smpling.py
from pprint import pprint
import os
from pathlib import Path
import random
import shutil
class FileControler(object):
    def make_file(self, output_dir, file_name, content='') -> None:
        """Création de fichier"""
        #Créer s'il n'y a pas de répertoire de destination de sortie
        os.makedirs(output_dir, exist_ok=True)
        #Combiner le répertoire de sortie et le nom de fichier
        file_path = os.path.join(output_dir, file_name)
        #Création de fichier
        with open(file_path, mode='w') as f:
            #Créer un fichier vide par défaut
            f.write(content)
    def get_files_path(self, input_dir, pattern):
        """Obtenir le chemin du fichier"""
        #Créer un objet chemin en spécifiant un répertoire
        path_obj = Path(input_dir)
        #Faire correspondre les fichiers au format glob
        files_path = path_obj.glob(pattern)
        #Conversion Posix à traiter comme une chaîne de caractères
        files_path_posix = [file_path.as_posix() for file_path in files_path]
        return files_path_posix
    def random_sampling(self, files_path, sampl_num, output_dir, fix_seed=True) -> None:
        """Échantillonnage aléatoire"""
        #Valeur de départ fixe lors de l'échantillonnage du même fichier à chaque fois
        if fix_seed is True:
            random.seed(0)
        #Spécifiez le chemin du groupe de fichiers et le nombre d'échantillons
        files_path_sampled = random.sample(files_path, sampl_num)
        #Créer s'il n'y a pas de répertoire de destination de sortie
        os.makedirs(output_dir, exist_ok=True)
        #copie
        for file_path in files_path_sampled:
            shutil.copy(file_path, output_dir)
file_controler = FileControler()
Créez 100 fichiers dans ʻinput /   Copiez le fichier échantillonné dans ʻinput / _sampled
all_files_dir = '../input'
sampled_dir = '../input/_sampled'
50 fichiers chacun de .py et .txt
for i in range(1, 51):
    file_controler.make_file(all_files_dir, f'file{i}.py')
    file_controler.make_file(all_files_dir, f'file{i}.txt')
from pprint import pprint
pattern = '*.py'
files_path = file_controler.get_files_path(all_files_dir, pattern)
pprint(files_path)
# ['../input/file8.py',
#  '../input/file28.py',
#  '../input/file38.py',
#  .
#  .
#  .
#  '../input/file25.py',
#  '../input/file35.py',
#  '../input/file50.py']
#
print(len(files_path))
# 50
sample_num = 10
file_controler.random_sampling(files_path, sample_num, sampled_dir)
Terminal
ls input/_sampled
file10.py file23.py file3.py  file35.py file36.py file37.py file38.py file4.py  file41.py file43.py
        Recommended Posts