f = open('./v al.txt')
lines = f.readlines() #整行读取
f.close()
for line in lines:
rs = line.rstrip('\n') #去除原来每行后面的换行符,但有可能是\r或\r\n
newname=rs.replace(rs,'/JPEGImages/'+rs+'.jpg'+' '+'/SegmentationClassAug/'+rs+'.png')
newfile=open('. val1.txt','a')
newfile.write(newname+'\n')
newfile.close()
在此记录下,用python将layout下的xml文件中的@dimen/dpxxx改为(xxx/3)dp。
批量替换文件夹下文件中某个字符
import os, shutil,re
if __name__=='__main__':
work_dir = 'C:\\Users\\Desktop\\workspace\\app\\src\\main\\res\\layout'
new_dir = 'C:\\Users\\Desktop\\layout_test\\'
for parent, dirnames, filenames in os.walk(work_dir, followlinks=True):
for filename in filenames:
file_path = os.path.join(parent, filename)
file = open(file_path,"r+",encoding='UTF-8')
newFile = open(new_dir+filename,"w",encoding='UTF-8')
for line in file.readlines():
if("@dimen/dp" in line):
num = re.sub("\D", "", line)
newNum = int(num)/3
newNum = ("%.1f" % newNum)
ori = line.split("\"")
line = line.replace(ori[1],str(newNum)+"dp")
newFile.writelines(line)
print (filename)
newFile.close()
file.close()
批量替换某个类名
import os, shutil,re
if __name__=='__main__':
work_dir = 'F:\\p1\\annotations'
new_dir = 'F:\\p1\\annotations_ship\\'
for parent, dirnames, filenames in os.walk(work_dir, followlinks=True):
for filename in filenames:
file_path = os.path.join(parent, filename)
file = open(file_path,"r+",encoding='UTF-8')
newFile = open(new_dir+'ship'+filename[4:],"w",encoding='UTF-8')
for line in file.readlines():
if("boat" in line):
line = line.replace("boat" ,"ship" )
newFile.writelines(line)
print (filename)
newFile.close()
file.close()
import os
path = r'C:\D\car_dataset\mark' # txt文件存放路径
sv_path = r'C:\D\car_dataset\labels' # 修改后的txt文件存放路径
files = os.listdir(path)
for txtFile in files:
txt_ab_route=path+"\\" + txtFile
write_ab_route=sv_path+"\\" + txtFile
# print(write_ab_route)
with open(txt_ab_route,'r') as txt: #'r+'表示对文件是进行"读取和写入的模式"
old_str = txt.read()
new_str='0'+old_str[1:-1]
# print(new_str)
# print(old_str)
txt.close()
f = open(write_ab_route,"a") #a表示没有该文件就新建
f.write(new_str) #写入文件
f.close() #执行完结束