python修改.txt文件中指定某些值

一、正文

我要把.txt文件中的,

F:/slide_dataSets/slide/Voc2007_1\JPEGImages\

换成

/content/drive/MyDrive/voc_2007_crack/Voc2007_1/data

原来txt文件格式:

F:/slide_dataSets/slide/Voc2007_1\JPEGImages\00524_270d.jpg 30,102,81,196,0 21,2,49,97,0 132,106,191,159,0 69,40,127,97,0
F:/slide_dataSets/slide/Voc2007_1\JPEGImages\00536_270d.jpg 107,115,170,197,0 44,29,103,107,0
F:/slide_dataSets/slide/Voc2007_1\JPEGImages\00545.jpg 102,27,153,111,0 62,136,113,197,0

代码实现:

import os
import argparse
import xml.etree.ElementTree as ET    

#保存.txt路径
save_file=open('/content/drive/MyDrive/voc_2007_crack/Voc2007_1/data/new_data_1.txt','w')  
#需要修改的TXT文件  
img_inds_file = os.path.join("/content/drive/MyDrive/voc_2007_crack/Voc2007_1/data/dataset/voc_train.txt")

with open(img_inds_file, 'r') as f:
  txt = f.readlines()
  image_inds = [line.strip() for line in txt]
  for image_ind in image_inds:
    annoth = '/content/drive/MyDrive/voc_2007_crack/Voc2007_1/JPEGImages/'
    annoth+=image_ind.split('\\')[-1]
    save_file.write(annoth+'\n')

结果:

/content/drive/MyDrive/voc_2007_crack/Voc2007_1/JPEGImages/00412.jpg 109,27,183,79,0 11,78,97,131,0
/content/drive/MyDrive/voc_2007_crack/Voc2007_1/JPEGImages/00469_90d.jpg 141,129,167,195,0 161,54,192,119,0 35,31,63,94,0 49,10,98,129,0
/content/drive/MyDrive/voc_2007_crack/Voc2007_1/JPEGImages/00239_90d.jpg 52,31,78,114,0 81,5,108,69,0
/content/drive/MyDrive/voc_2007_crack/Voc2007_1/JPEGImages/00357_90d.jpg 4,61,199,132,0
全部评论

相关推荐

评论
点赞
收藏
分享
牛客网
牛客企业服务