需要替换几个文本文件中每行的首字。

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

我需要替换许多文本文件(注释文件)中每行的第一个字(标签)。我已经写了下面的脚本,但它没有在文本文件中做出任何改变。

 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

我是否必须使用 文件输入 模块来实现这个目的?

你可以在下面找到一个示例.txt(注释)内容:''''

0 0.15234375 0.6953125 0.2265625 0.053125

0 0.75078125 0.27890625 0.2046875 0.1546875

0 0.28359375 0.09296875 0.1734375 0.0734375

10 0.31015625 0.634375 0.0890625 0.2625

9 0.37109375 0.35703125 0.0671875 0.2015625

3 0.13671875 0.32265625 0.1609375 0.1390625

1 0.90390625 0.55 0.1390625 0.059375

1 0.946875 0.67890625 0.075 0.0515625

1 0.84921875 0.76171875 0.1609375 0.0515625

3 0.82578125 0.1296875 0.0796875 0.0875

'''先谢谢你!

python python-3.x error-handling label
1个回答
1
投票

正如其他人所提到的,你的改变不会传播到输出中。

这让我更清楚地知道你应该怎么做。

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:
        # Don't read entire file since we
        # are looping line by line
        #infile = f.read()# Read contents of file
        result = []
        for line in f:  # changed to file handle
            line = line.rstrip() # remove trailing '\n'
            # Only split once since you're only check the first word
            words = line.split(" ", maxsplit = 1)
            word = words[0]  # word 0 may change
            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:
                pass
            # Update the word you modified
            words[0] = word  # update word 0
            # save new line into results
            # after converting back to string
            result.append(" ".join(words))

    with open(os.path.join(dirname, txt_in), 'w') as f:
        # Convert result list to string and write to file
        outfile = '\n'.join(result)
        f.write(outfile)

1
投票

你创建了行和字这样的变量,并对它们进行了修改,但这些修改并没有反映在 infile. 您需要对以下内容进行修改 infile 本身,或者将更改后的内容存储在一个新的变量中,并将新变量写入新文件。

你可以把代码更新为。

outfile = ""
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:
                pass
            newLine = ""
            newLine += word
            for w in line.split(" ")[1:]:
                newLine += w
            newLine += "\n"
            outfile += newLine

现在把outfile写到outputfile里


0
投票

我认为问题出在路径上,"dirname "的结尾需要一个''。无论是哪种方式,你可能想要检查的第一件事是文件是否有效。


for txt_in in os.listdir(dirname):

    print(os.path.isfile(os.path.join(dirname, txt_in)))

    with open(os.path.join(dirname, txt_in), 'r') as f:


0
投票

与其尝试编辑你正在阅读的文件,我建议采用不同的方法。

  1. 创建一个新的文件,包含所有的更改,保存它。
  2. 删除原文件。
  3. 将新文件重新命名为原始文件。
import os


dirname = "/home/masoud/masoud/Dataset/PID-CORRECTED/uncorrected-YOLO_darknet"
for txt_in in os.listdir('uncorrected-YOLO_darknet'):
    with open(os.path.join(dirname, txt_in), 'r') as f:
        out_filename = txt_in+"1"
        out_file = open(out_filename, "w")

        for line in f.readlines():
            word = line[0]
            if word == "6":
                line = line.replace('6', '5')
            elif word =="9":
                line = line.replace('9', '6')
            elif word == "10":
                line = line.replace('10', '7')
            elif word == "11":
                line = line.replace('11', '8')
            else:
                continue

            out_file.write(line)
        out_file.close()

    os.remove(os.path.join(dirname, txt_in))
    os.rename(os.path.join(dirname, out_filename), os.path.join(dirname, txt_in))


0
投票

你可以直接做一个列表,并将更改后的单词追加到列表中,然后你可以通过file_object.writelines(list)将其写出来。

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.readlines()# Read contents of file
        d=[]
        for line in infile:
            word = line.split(" ")
            if word[0]=="6":
                word[0]="5"
            elif word[0]=="9":
                word[0]= '6'
            elif word[0]=="10":
                word[0]= '7'
            elif word[0]=="11":
                word[0]= '8'
            d.append(" ".join(word))
        if len(d)!=0:
            f.seek(0)
            f.writelines(d)
© www.soinside.com 2019 - 2024. All rights reserved.