程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python modifies the image name in the txt file by line

編輯:Python

Basics : Divide the data set into 3 class :train/test/val. utilize txt File the name of the saved image .

Considering convenience , Will now txt Rename the image name in the file , Read multiple... Containing image names txt file , Prefix the image name .

Revised as follows :

txt file : Original image name ---> Modified image name

[txt_name].txt:[name].png  ---> [txt_name]_[name].png

# encoding: utf-8
'''
Read multiple... Containing image names txt file , Prefix the image name .
Contains the name of each image after the data set is divided txt file :train.txt,test.txt,val.txt
txt file : Original image name ---> Modified image name
train: 2045.png ---> train_2045.png
test: 3873.png ---> test_3873.png
val: 6154.png ---> val_6154.png
'''
import os
import random
def read_file(filepath,txt_name):
file_list=[]
list2=[]
with open(filepath,'r') as fr:
data = fr.readlines()
data = ''.join(data).strip('\n').splitlines()
file_list=data
# print(file_list)
txt0=txt_name.split('.')[0]
for line in file_list:
line=txt0+'_'+line
list2.append(line)
return list2
def write_file(dst1,txt):
fo=open(dst1,'w')
for item in txt:
fo.write(str(item)+'\n')
if __name__ == "__main__":
root_path=r'F:\all_date\WHU'
txts=['train.txt','test.txt','val.txt']
for txt_name in txts:
to_path=os.path.join(root_path,txt_name)
txt_list=read_file(to_path,txt_name)
write_file(to_path,txt_list)

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved