【问题标题】:How to modify the value of a Yolo .txt file in python如何在python中修改Yolo .txt文件的值
【发布时间】:2021-06-05 06:35:55
【问题描述】:

我想用 .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

你能帮帮我吗?

【问题讨论】:

  • 请提供您目前尝试过的代码。

标签: python python-3.x txt


【解决方案1】:

我认为这段代码应该去。 让我知道您是否打算这样做。

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()

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

【讨论】:

  • 是的,但是,如果我有一个包含我想要更改的那些 .txt 文件的文件夹会发生什么。我至少要阅读和更改 100 个 txt 文件。
  • 我也有这个错误: Traceback(最近一次调用最后一次):文件“find2.py”,第 14 行,在 temp = float(i[0]) - 1 ValueError: could不将字符串转换为浮点数:
  • 已更新。在 listdir 中,您应该使用 txt 文件添加文件夹的路径
  • 发生了什么事。看起来没有文件:files.append() TypeError: append() 只接受一个参数(给定 0)
  • 也更新了。
猜你喜欢
  • 1970-01-01
  • 2020-03-30
  • 2022-06-28
  • 1970-01-01
  • 1970-01-01
  • 2022-01-05
  • 2022-12-19
  • 2012-11-27
  • 2012-04-16
相关资源
最近更新 更多