As a beginner with Python, I am trying to run the following code to replace some labels in .txt annotation files.
import os
dirname = "/home/masoud/masoud/Dataset/PID-CORRECTED/uncorrected-YOLO_darknet"
for txt_in in os.listdir(dirname):
with open(os.path.join(dirname, txt_in), 'r') as f:
infile = f.read()# Read contents of file
for line in infile.split('\n') :
word=line.split(" ")[0]
if word=="6":
word=word.replace('6', '5')
elif word=="9":
word=word.replace('9', '6')
elif word=="10":
word=word.replace('10', '7')
elif word=="11":
word=word.replace('11', '8')
else:
continue
with open(os.path.join(dirname, txt_in), 'w') as f:
f.write(infile)
break
How can I nest each replacement inside of my text file?
Also, my .txt file which is my annotations looks like this:
- 10 0.31015625 0.634375 0.0890625 0.2625
- 9 0.37109375 0.35703125 0.0671875 0.2015625