I'm still very new to programming with Python 3 and know almost nothing about it. I was told that Python is both powerful and easy to learn.
Right now I'm trying to rename some .jpg files from my android phone into a certain pattern. The usual pattern of a normal .jpg file(taken with the camera) from my android phone looks like this: YYYYMMDD_hhmmss.jpg
and im trying to change it into this pattern: YYYY-MM-DD hh-mm-ss.jpg
This is the code i wrote so far:
import re
import os
for filename in os.listdir(".") #here is the path to the .jpg files
m = re.match(r"(\d{8})_(\d{6})\.jpg", filename)
if m:
newname = (r"(\d{4})-(\d{2})-(\d{2}) (\d{2})-(\d{2})-(\d{2})\.jpg)
if not os.path.exists(newname):
os.rename(filename, newname)
When i run the program the shell alone doesn't really show me an error message. It only says this:
=====RESTART: (a path that leads to the .py file that my code is written in)======
After that i ran the debugger through the Python Shell and it said:
KeyError:(, '(\d{8})_(\d{6})\.jpg'0) (in the debugger)
_tkinter.TclError: invalid command name ".47860048.41027664.41027120" (in the shell after debugging)
I dont know what it means or what i can do to make this work.
Thanks in advance for every answer i might get.
You should use re.sub
and backreference
import re
import os
FOLDER_PATH = "." #set your path here
for filename in os.listdir(FOLDER_PATH):
newname = re.sub("(\d{4})(\d{2})(\d{2})_(\d{2})(\d{2})(\d{2})\.jpg"
, r"\1-\2-\3 \4-\5-\6.jpg"
, filename)
if (newname != filename and (not os.path.exists(os.path.join(FOLDER_PATH, newname)))):
os.rename(os.path.join(FOLDER_PATH, filename), os.path.join(FOLDER_PATH, newname))