[英]Rename multiple file of different extension with the same name in the incremental order
I have multiple folders in which I have files named as follows:我有多个文件夹,其中的文件命名如下:
1500001.jpg
1500001.xml
1600002.jpg
1600002.xml
9876543.jpg
9876543.xml
As you can see I have one jpg file and its corresponding xml file with the same file name.如您所见,我有一个 jpg 文件及其对应的 xml 文件,文件名相同。 I want to rename all these files as follows:
我想将所有这些文件重命名如下:
ID_0001.jpg (1500001.jpg converted to ID_0001.jpg)
ID_0001.xml (1500001.xml converted to ID_0001.xml)
ID_0002.jpg (1600002.jpg converted to ID_0002.jpg)
ID_0002.xml (1600002.xml converted to ID_0002.xml
ID_0003.jpg (9876543.jpg converted to ID_0003.jpg)
ID_0003.xml (9876543.xml converted to ID_0003.xml)
I am new to Python and have written some code for renaming files with different extension but not able to scale this to keeping the same filename for its corresponding file in the incremental order like ID_0001.jpg, ID_0001.xml, etc.我是 Python 的新手,并且已经编写了一些代码来重命名具有不同扩展名的文件,但无法将其扩展为以增量顺序保持其相应文件的相同文件名,例如 ID_0001.jpg、ID_0001.xml 等。
import os
_src = "path/to/directory"
_ext_jpg = ".jpg"
_ext_xml = ".xml"
for i,filename in enumerate(os.listdir(_src)):
if filename.endswith(_ext_jpg):
os.rename(filename, _src+'ID_' + str(i)+_ext_jpg)
else:
os.rename(filename, _src+'ID_' + str(i)+_ext_xml)
With this code, the increment happens for the all the files like ID_0001.jpg, ID_002.xml, ID_003.jpg, ID_004.xml and actually it should be like ID_0001.jpg, ID_0001.xml, ID_0002.jpg, ID_0002.xml, etc. With this code, the increment happens for the all the files like ID_0001.jpg, ID_002.xml, ID_003.jpg, ID_004.xml and actually it should be like ID_0001.jpg, ID_0001.xml, ID_0002.jpg, ID_0002.xml,等等
When you get a filename, rename both the xml
and jpg
files:获得文件名后,重命名
xml
和jpg
文件:
import os
_src = "path/to/directory"
_ext_jpg = ".jpg"
_ext_xml = ".xml"
for i,filename in enumerate(os.listdir(_src)):
if filename.endswith(_ext_jpg):
os.rename(filename, _src+'ID_' + str(i)+_ext_jpg)
os.rename(filename[:-4]+_ext_xml, _src+'ID_' + str(i)+_ext_xml)
Using glob
使用
glob
Ex:前任:
import os
import glob
_src = "path/to/directory"
for i,filename in enumerate(glob.glob("{}*.jpg".format(_src))):
file = os.path.basename(filename)
f, ext = os.path.splitext(file)
os.rename(filename, os.path.join(_src, 'ID_' + str(i)+ext)) #Rename .jpg
os.rename(os.path.join(_src, "{}.xml".format(f) , os.path.join(_src, 'ID_' + str(i)+".xml")) #Rename .xml
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.