首页 > 解决方案 > 想在python中重命名2个具有不同扩展名的文件

问题描述

我正在一个项目中工作,我需要重命名同一文件夹中的多个文件,为此我写下了代码,但是当我运行此代码时,它会抛出“文件已存在”之类的错误。有什么方法可以跳过那些已经存在于 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   

标签: python

解决方案


请确保将您的文件夹复制为备份,因为这将删除您的旧文件夹,而是放置一个具有相同名称的新文件夹,以防万一出现任何问题。

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 的文件夹的路径。
输出将生成在名为Out的文件夹中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 列表pngsxmls写下所选文件的二进制数据,该文件的名称由输出路径对象位置中的枚举索引指定。

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)

推荐阅读