我如何使用 python 3 以特定模式重命名 android phone 的 .jpg 文件?
How can i rename an android phone's .jpg file in a specific pattern using python 3?
我对使用 Python 3 进行编程还是很陌生,对此几乎一无所知。有人告诉我 Python 既强大又易于学习。
现在我正在尝试将 android phone 中的一些 .jpg 文件重命名为特定模式。来自我的 android phone 的普通 .jpg 文件(用相机拍摄)的通常模式看起来像这样:YYYYMMDD_hhmmss.jpg
我正在尝试将其更改为这种模式:YYYY-MM-DD hh-mm-ss.jpg
这是我到目前为止写的代码:
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)
当我 运行 程序时 shell 并没有真正向我显示错误消息。
它只说:
=====RESTART: (a path that leads to the .py file that my code is written in)======
之后我 运行 调试器通过 Python Shell 它说:
KeyError:(, '(\d{8})_(\d{6})\.jpg'0) (in the
debugger)
_tkinter.TclError: invalid command name ".47860048.41027664.41027120" (in the shell after debugging)
我不知道这意味着什么,也不知道我能做些什么来完成这项工作。
提前感谢我可能得到的每一个答案。
你应该使用 re.sub
和 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"-- --.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))
我对使用 Python 3 进行编程还是很陌生,对此几乎一无所知。有人告诉我 Python 既强大又易于学习。
现在我正在尝试将 android phone 中的一些 .jpg 文件重命名为特定模式。来自我的 android phone 的普通 .jpg 文件(用相机拍摄)的通常模式看起来像这样:YYYYMMDD_hhmmss.jpg
我正在尝试将其更改为这种模式:YYYY-MM-DD hh-mm-ss.jpg
这是我到目前为止写的代码:
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)
当我 运行 程序时 shell 并没有真正向我显示错误消息。 它只说:
=====RESTART: (a path that leads to the .py file that my code is written in)======
之后我 运行 调试器通过 Python Shell 它说:
KeyError:(, '(\d{8})_(\d{6})\.jpg'0) (in the debugger)
_tkinter.TclError: invalid command name ".47860048.41027664.41027120" (in the shell after debugging)
我不知道这意味着什么,也不知道我能做些什么来完成这项工作。
提前感谢我可能得到的每一个答案。
你应该使用 re.sub
和 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"-- --.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))