簡體   English   中英

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

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

我正在一個項目中工作,我需要重命名同一文件夾中的多個文件,為此我寫下了代碼,但是當我運行此代碼時,它會拋出“文件已經存在”之類的錯誤。 有什么方法可以跳過那些已經存在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名為Out的文件夾中生成。

例子:
說你的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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM