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

标签 python python-3.x txt

我想修改包含 .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()

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

关于python - 如何在python中修改Yolo .txt文件的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66511872/

相关文章:

R:将 "dput"的输出保存在 txt 文件中

python - 如何从txt文件制作字典?

python - 如何创建 Python stub 文件以及放置在哪里?

Python 类型错误 : can't multiply sequence by non-int of type 'float'

python - 在 mongoengine 中查询投影

python - 了解 pandas groupby/apply 行为

python - 循环遍历表单 POST 将数据存储在 python 变量中

Python 3 特殊字符转义

python - 仅列出子进程中的文件和目录名称 ls -l