简体   繁体   English

想在python中重命名2个具有不同扩展名的文件

[英]want to rename 2 files with different extension in python

I am working in one project where i need to rename the multiple file in same folder and for that i write down the code but when i am running this code then it's throwing the error like "file already exist".我正在一个项目中工作,我需要重命名同一文件夹中的多个文件,为此我写下了代码,但是当我运行此代码时,它会抛出“文件已经存在”之类的错误。 is there any way where i can skip those file which is already present with sequqnce and rename the rest of file in sequence, please help me.有什么方法可以跳过那些已经存在sequqnce的文件并按顺序重命名文件的其余部分,请帮助我。

Example of file:文件示例:

0.png
0.xml 

Code which i wrote:我写的代码:

    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   

Please make sure to copy your folder as backup as this will remove your old folder and instead will place a new folder with same name this is just in case anything goes wrong.请确保复制您的文件夹作为备份,因为这将删除您的旧文件夹,而是放置一个同名的新文件夹,以防万一出现问题。

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)

change the base_dir variable to path of your folder containing images and xmls.base_dir变量更改为包含图像和xml的文件夹的路径。
output will be generated in the folder named Out in the current working directory .输出将在current working directory名为Out的文件夹中生成。

Example:例子:
say your annotate folder looks like this说你的annotate文件夹看起来像这样

/Annotate
--/0.png
--/0.xml
--/1.png
--/1.xml
--/dog.png
--/dog.xml
--/cat.png
--/cat.xml

After running the script The Annotate folder will look like.运行脚本后, Annotate文件夹将如下所示。

/Annotate
--/0.png
--/0.xml
--/1.png
--/1.xml
--/2.png
--/2.xml
--/3.png
--/3.xml

I am not exactly renaming the file but I am making a new directory with file naming format you want.我并没有完全重命名文件,但我正在使用您想要的文件命名格式创建一个新目录。

NOTE:笔记:
If you annotate more images ie you run the script again after annotating more images I would recommend that you delete the old Output folder.如果您注释更多图像,即在注释更多图像后再次运行脚本,我建议您删除旧的输出文件夹。 It should not matter though but for safety!!不过为了安全应该没关系!!
Make sure you have latest python installed.

As per request, here is the step by step code explanation!根据要求,这里是一步一步的代码解释!

you import required module您导入所需的模块

from pathlib import Path

make two path objects :制作两个路径对象
1. directory specifying your input directory path. 1. directory指定您输入的目录路径。
2. out_dir specifying path to temporary output folder 2. out_dir指定临时输出文件夹的路径

directory = Path("./Annotate")
out_dir = Path("./Out")

Makes a folder specified in the Path object, if folder exists no error is thrown the code continues.创建在 Path 对象中指定的文件夹,如果文件夹存在,则不会引发错误代码继续。

out_dir.mkdir(exist_ok=True)

Makes two separate python list of all the paths inside the selected path object that ends with .png and .xml .为所选路径对象内的所有路径创建两个单独的 python 列表,以.png.xml结尾。

pngs = list(directory.glob("*.png"))
xmls = list(directory.glob("*.xml"))

loops through the python list pngs and xmls and writes down binary data of selected file with the name specified by index of enumerate in the output path object location.循环遍历 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())

Deletes everything from the path object specified.从指定的路径对象中删除所有内容。
than remove the path object.比删除路径对象。 and rename the temporary path object to old path that was just removed.并将临时路径对象重命名为刚刚删除的旧路径。

for files in directory.iterdir():
    files.unlink()

directory.rmdir()
out_dir.rename(directory)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM