我在一个项目中工作,我需要重命名同一文件夹中的多个文件,为此我写下了代码,但是当我运行此代码时,它会抛出“文件已经存在”之类的错误。有什么方法可以跳过那些已经存在sequqnce的文件并按顺序重命名文件的其余部分,请帮助我。
文件示例:
0.png
0.xml
我写的代码:
import os
png_files = set()
xml_files = set()
base_path = r'C://Users//admin//Desktop//anotate'
for x in os.listdir(base_path):
name, ext = x.split('.')
if ext == 'png':
png_files.add(name)
elif ext == 'xml':
xml_files.add(name)
counter = 0
for filename in png_files.intersection(xml_files): # For files that are common (same names)
if filename.exists():
print ("File exist")
else:
os.rename(os.path.join(base_path,filename+'.png'),os.path.join(base_path,str(counter)+'.png'))
#Rename png file
os.rename(os.path.join(base_path,filename+'.xml'),os.path.join(base_path,str(counter)+'.xml')) #
Rename xml file
counter += 1 # Increment counter
from pathlib import Path
directory = Path("./Annotate")
out_dir = Path("./Out")
out_dir.mkdir(exist_ok=True)
pngs = list(directory.glob("*.png"))
xmls = list(directory.glob("*.xml"))
for num, file in enumerate(pngs):
write_here = out_dir / "{}.png".format(num)
write_here.write_bytes(file.read_bytes())
for num, file in enumerate(xmls):
write_here = out_dir / "{}.xml".format(num)
write_here.write_bytes(file.read_bytes())
for files in directory.iterdir():
files.unlink()
directory.rmdir()
out_dir.rename(directory)
将base_dir变量更改为包含图像和xml的文件夹的路径。
输出命名的文件夹中产生出的current working directory
。
示例:
假设您的annotate
文件夹如下所示
/Annotate
--/0.png
--/0.xml
--/1.png
--/1.xml
--/dog.png
--/dog.xml
--/cat.png
--/cat.xml
运行脚本后Annotate
文件夹将如下所示。
/Annotate
--/0.png
--/0.xml
--/1.png
--/1.xml
--/2.png
--/2.xml
--/3.png
--/3.xml
我并没有完全重命名文件,但我正在使用您想要的文件命名格式创建一个新目录。
注意:
如果您注释更多图像,即在注释更多图像后再次运行脚本,我建议您删除旧的输出文件夹。不过为了安全应该没关系!!
Make sure you have latest python installed.
您导入所需的模块
from pathlib import Path
制作两个路径对象:
1.directory
指定您的输入目录路径。
2.out_dir
指定临时输出文件夹的路径
directory = Path("./Annotate")
out_dir = Path("./Out")
创建在 Path 对象中指定的文件夹,如果文件夹存在,则不会引发错误代码继续。
out_dir.mkdir(exist_ok=True)
为所选路径对象内的所有路径创建两个单独的 python 列表,以.png
和结尾.xml
。
pngs = list(directory.glob("*.png"))
xmls = list(directory.glob("*.xml"))
循环遍历 python 列表pngs
并xmls
记下所选文件的二进制数据,其名称由输出路径对象位置中的枚举索引指定。
for num, file in enumerate(pngs):
write_here = out_dir / "{}.png".format(num)
write_here.write_bytes(file.read_bytes())
for num, file in enumerate(xmls):
write_here = out_dir / "{}.xml".format(num)
write_here.write_bytes(file.read_bytes())
从指定的路径对象中删除所有内容。
比删除路径对象。并将临时路径对象重命名为刚刚删除的旧路径。
for files in directory.iterdir():
files.unlink()
directory.rmdir()
out_dir.rename(directory)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句