Другой вариант заключается в том, что сценарий помещает эти файлы в уже существующие папки, поскольку у меня есть каталог шаблонов с пустыми папками.
Разделение необходим для того, чтобы программное обеспечение печати могло распечатывать эти пакеты отдельно. Кроме того, мне нужно знать, какой файл находится в какой папке. Нужно отсортировать около 3800 PDF-файлов.
Как только я разберусь, как получить эти папки, я смогу завершить проект, создав список файлов в папке.
Это код на данный момент, который создает новые папки и называет их по первому файлу в пакете.
Код: Выделить всё
import os
import shutil
source_directory = "//All-the-data"
Destination_base_folder = '//All-the-data/sorted'
batch_size = 50
# check if source directory exists
if os.path.exists(source_directory) and os.path.isdir(source_directory):
# get all the files
files = os.listdir(source_directory)
# Sort files by filename
files.sort()
counter = 1
for i in range(0, len(files), batch_size):
# create a folder for each batch
batch_directory_name = os.path.splitext(files[i])[0]
batch_directory_path = os.path.join(Destination_base_folder, batch_directory_name)
os.makedirs(batch_directory_path, exist_ok=True)
# copy files into these folders
for j in range(min(batch_size, len(files) - i)):
source_file_path = os.path.join(source_directory, files[i + j])
destination_file_path = os.path.join(batch_directory_path, files[i + j])
shutil.copy2(source_file_path, destination_file_path)
print(f"Batch {counter} erfolgreich nach {batch_directory_path} kopiert")
counter += 1
else:
print("Quellordner existiert nicht: " + source_directory)
Код: Выделить всё
def number_folders_chronologically(destination_folder):
batch_folders = [folder for folder in os.listdir(destination_folder) if os.path.isdir(os.path.join(destination_folder, folder))]
batch_folders.sort(key=lambda x: os.path.getctime(os.path.join(destination_folder, x)))
for index, folder in enumerate(batch_folders, start=1):
old_path = os.path.join(destination_folder, folder)
new_folder_name = f"{index:03d}_{folder}"
new_path = os.path.join(destination_folder, new_folder_name)
os.rename(old_path, new_path)
Спасибо всем за помощь.
Подробнее здесь: https://stackoverflow.com/questions/781 ... -in-python