在Python中,可以使用os
模块来重命名和复制文件。下面是使用子文件夹名称重命名并高效地复制Python中的文件的步骤:
os
模块:import os
source_folder = '源文件夹路径'
target_folder = '目标文件夹路径'
for filename in os.listdir(source_folder):
source_file = os.path.join(source_folder, filename)
if os.path.isfile(source_file):
# 执行重命名和复制操作
subfolder_name = os.path.basename(os.path.dirname(source_file))
new_filename = subfolder_name + '_' + filename
target_file = os.path.join(target_folder, new_filename)
with open(source_file, 'rb') as src_file, open(target_file, 'wb') as dst_file:
dst_file.write(src_file.read())
完整代码示例:
import os
source_folder = '源文件夹路径'
target_folder = '目标文件夹路径'
for filename in os.listdir(source_folder):
source_file = os.path.join(source_folder, filename)
if os.path.isfile(source_file):
subfolder_name = os.path.basename(os.path.dirname(source_file))
new_filename = subfolder_name + '_' + filename
target_file = os.path.join(target_folder, new_filename)
with open(source_file, 'rb') as src_file, open(target_file, 'wb') as dst_file:
dst_file.write(src_file.read())
这样,你就可以使用子文件夹名称重命名并高效地复制Python中的文件了。
腾讯云相关产品和产品介绍链接地址:
领取专属 10元无门槛券
手把手带您无忧上云