我想重命名多个文件夹。
示例文件夹结构:
Main_Folder|
|winter(2017-12-18)
|summer(2018-03-26)
很多时候我将许多图片保存到许多不同的文件夹中,但是我不记得我将图片保存到哪个文件夹中。
我要实现的示例:
夏天(2018-03-26)当我将新图片保存到该文件夹并运行程序时 ,我希望程序将该文件夹重命名为summer(2018-08-14)<-这是该文件夹的修改日期
import os
import datetime
def modifiedFolderName(folderdir):
target = folderdir
allFolder = os.listdir(target)
for foldername in allFolder:
checkname = foldername.find("(")
if checkname != -1 #if that folder don't have modified date skip it
#need help here
time = os.path.getmtime(foldername)
#
#
#
os.rename(foldername,trimFolderName(foldername)+"("+"new modified date"+")")
def trimFolderName(foldername):
a1 = foldername
b1 = a1.find("(")
a2 = a1[0:b1]
return a2 #return folder name without modified date
def main():
modifiedFolderName("") #for folder dir
if __name__ == "__main__":
main()
答案 0 :(得分:0)
参考文献:
解决方案:
time = os.path.getmtime(foldername)
lastModified = datetime.datetime.fromtimestamp(time)
lastModifiedStr = lastModified.strftime("(%Y-%m-%d)")
# just for debugging, to see what it is doing
print("Last modified: %s", lastModifiedStr)
newFolderName = trimFolderName(foldername)+lastModifiedStr
os.rename(foldername, newFolderName)