Reputation: 33
I want to rename photos in folder by it's date. This is my python script.
import os
from datetime import datetime
folder_name = 'D:/Users/user/Desktop/Xiomi/100ANDRO/'
dir_list = [os.path.join(folder_name, x) for x in os.listdir(folder_name)]
for file in dir_list:
filename, file_extension = os.path.splitext(file)
date = datetime.fromtimestamp(os.path.getctime(file)).strftime('%Y_%m_%d_%H_%M_%S')
os.rename(os.path.basename(file), date + file_extension)
print(dir_list)
But I have an error:
$ python script.py
Traceback (most recent call last):
File "script.py", line 10, in <module>
os.rename(os.path.basename(file), date + file_extension)
FileNotFoundError: [WinError 2] ▒▒ ▒▒▒▒▒▒▒ ▒▒▒▒▒ ▒▒▒▒▒▒▒▒▒ ▒▒▒▒:
'DSC_0003.JPG' -> '2018_07_08_12_28_21.JPG'
The file is definitely in folder. Can you help me with it?
Upvotes: 1
Views: 3321
Reputation: 2939
Looks to me like you need to give os.rename()
the absolute path to the file
os.rename(file, os.path.join(folder_name, date + file_extension))
Upvotes: 1
Reputation: 140168
Why are you taking the base name from the target when the absolute path would be okay ?
os.rename
works on files that exist. It works if you pass absolute paths provided that the files are located on the same drive. I'd do:
os.rename(file, os.path.join(folder_name,date + file_extension))
basically remove the basename, and add the folder name for the destination. Since the directory is the same for both, that'll work. And it's much cleaner than a dirty os.chdir(folder_name)
Upvotes: 2