python 如何修改 Yolo .txt 文件的值

How to modify the value of a Yolo .txt file in python

我想修改包含 .txt 文件的文件夹

txt 文件如下所示:

3 0.695312 0.523958 0.068750 0.052083
3 0.846875 0.757292 0.071875 0.031250
3 0.830469 0.719792 0.067187 0.035417

我的想法是获取所有 .txt 文件并内联更改第一个数字。

输出示例:

2 0.695312 0.523958 0.068750 0.052083
2 0.846875 0.757292 0.071875 0.031250
2 0.830469 0.719792 0.067187 0.035417

你能帮帮我吗?

我认为这段代码应该去。 如果您打算这样做,请告诉我。

import os

files = []
# Add the path of txt folder
for i in os.listdir("C:\data"):
    if i.endswith('.txt'):
        files.append(i)

for item in files:
    # define an empty list
    file_data = []

    # open file and read the content in a list
    with open(item, 'r') as myfile:
        for line in myfile:
            # remove linebreak which is the last character of the string
            currentLine = line[:-1]
            data = currentLine.split(" ")
            # add item to the list
            file_data.append(data)
    
    # Decrease the first number in any line by one
    for i in file_data:
        if i[0].isdigit():
            temp = float(i[0]) - 1
            i[0] = str(int(temp))

    # Write back to the file
    f = open(item, 'w')
    for i in file_data:
        res = ""
        for j in i:
            res += j + " "
        f.write(res)
        f.write("\n")
    f.close()

这个程序读取一个文件并将任何行中的所有第一个数字减一个。然后将其写回文件。