我有一个代码,采取一个文件夹的文件,并把他们在批50到新的文件夹.现在我想脚本命名这些文件夹数字和开始与1. 另一种 Select 是脚本将这些文件放在已经存在的文件夹中,因为我有一个模板目录,文件夹为空. 拆分是必要的,这样打印软件将能够吐出这些批次单独.此外,我需要知道哪个文件在哪个文件夹.大约有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)
之后,我try 了以下重命名文件夹的方法.哪个文件在哪个文件夹中并不重要.
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)
我对使用Python编程是完全陌生的,我已经15年没有编程了.即使是在那个时候,我的知识也是基本的.我非常确定解决方案是完全容易的,我只是看不出来.
谢谢大家的帮助.