以下是一个示例代码,演示如何按照首字母拆分文件:
import os
import shutil
def split_files_by_first_letter(source_folder, destination_folder):
# 确保目标文件夹存在
if not os.path.exists(destination_folder):
os.makedirs(destination_folder)
# 遍历源文件夹中的文件
for file_name in os.listdir(source_folder):
source_file = os.path.join(source_folder, file_name)
if os.path.isfile(source_file):
# 获取文件名的首字母
first_letter = file_name[0].upper()
# 创建首字母对应的文件夹
destination_folder_letter = os.path.join(destination_folder, first_letter)
if not os.path.exists(destination_folder_letter):
os.makedirs(destination_folder_letter)
# 拷贝文件到对应的文件夹中
destination_file = os.path.join(destination_folder_letter, file_name)
shutil.copy2(source_file, destination_file)
source_folder = "源文件夹路径"
destination_folder = "目标文件夹路径"
split_files_by_first_letter(source_folder, destination_folder)
请将示例代码中的源文件夹路径
和目标文件夹路径
替换为实际的文件夹路径。此代码将遍历源文件夹中的文件,根据文件名的首字母将文件拷贝到对应的文件夹中。例如,文件名为"example.txt"的文件将被拷贝到目标文件夹中的"E"文件夹中。
上一篇:按首个字符出现的次数计数
下一篇:按首字母的出现拆分列