需求:将文件夹的前13位数字提取出来,添加为文件夹下每个文件的前缀,前13位是时间戳。
python中的shutil模块可以实现文件的复制、移动、重命名。
#复制文件:
shutil.copyfile("oldfile","newfile") #oldfile和newfile都只能是文件
shutil.copy("oldfile","newfile") #oldfile只能是文件夹,newfile可以是文件,也可以是目标目录
#复制文件夹:
shutil.copytree("olddir","newdir") #olddir和newdir都只能是目录,且newdir必须不存在
#重命名文件(目录)
os.rename("oldname","newname") #文件或目录都是使用这条命令
#移动文件(目录)
shutil.move("oldpos","newpos")
shutil.move("D:/知乎日报/latest/", "D:/知乎日报/past/")
import os
import shutil
folder_path = "/Users/PycharmProjects/TimeStampRename/datas"
folder = os.listdir(folder_path)
for foldername in folder:
s = foldername[0:13]
print(foldername)
image_list = os.listdir(folder_path + "/" +foldername)
for i in image_list:
print(i)
image_path = folder_path + "/" + foldername + "/" + i
target_path = folder_path + "/" + foldername + "/" + s + "_" + i
print(target_path)
shutil.move(image_path, target_path)
结果: