0

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
Russ Cam
  • 124,184
  • 33
  • 204
  • 266
Max
  • 509
  • 1
  • 7
  • 21

1 Answers1

1

You're not writing anything to the file. You need to read the file, do something with the text you obtain, and then write that text back to the file:

# Read contents of file
with open(os.path.join(dirname, txt_in), 'r') as f:
    infile = f.read()

# Do something with infile ... e.g. :
for line in infile.split('\n') :
    pass # your code here instead of 'pass'



# Write to file
with open(os.path.join(dirname, txt_in), 'w') as f:
    f.write(infile)
SimonR
  • 1,774
  • 1
  • 4
  • 10