如何使用Python在.txt文件中嵌套“替换的对象”

问题描述 投票:0回答:1

我是Python的初学者。我正在尝试运行以下代码来替换.txt批注文件中的某些标签。

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)) as infile:
        for line in infile:
            word=line.split(" ")[0]#spliting the string and returning an array and returing the first item of array
            if word=="6":
                word=word.replace('6', '5')#it is only changing the word but not in the infile
            elif word=="9":
                word=word.replace('9', '6')
            elif word=="10":
                word=word.replace('10', '7')
            elif word=="11":
                word=word.replace('11', '8')
                #If the break statement is inside a nested loop (loop inside another loop), the break statement will terminate the innermost loop.
            else:
                continue
            break 

显然,它仅更改“ word”对象,而不更改“ infile”(每个.txt文件)内的内容。提前非常感谢您的帮助!我的.txt文件(即我的注释)如下所示:

10 0.31015625 0.634375 0.0890625 0.2625

    9 0.37109375 0.35703125 0.0671875 0.2015625
  • 我是Python的初学者。我正在尝试运行以下代码来替换.txt批注文件中的某些标签。 import os dirname =“ / home / masoud / masoud / Dataset / PID-CORRECTED / uncorrected -...
  • python arrays label nest
    1个回答
    0
    投票
    最新问题
    © www.soinside.com 2019 - 2024. All rights reserved.