0

我正在读取一个文本文件并根据某些条件逐行搜索数据,更改该行中的某些值并将其写回另一个文件。新文件不应包含旧行。我尝试了以下方法,但没有奏效。我想我错过了一个非常基本的东西。

解决方案:在 C++ 中我们可以增加行,但在 Python 中我不知道如何实现这一点。所以到目前为止,我写的是旧行而不是新行。但是在新文件中,我只想要新行。

例子:

M0 38 A 19 40 DATA2 L=4e-08 W=3e-07 nf=1 m=1 $X=170 $Y=140 $D=8
M0 VBN A 19 40 TEMP2 L=4e-08 W=3e-07 nf=1 m=1 $X=170 $Y=140 $D=8 

我尝试的代码如下:

def parsefile():
    fp = open("File1", "rb+")
    update_file = "File1" + "_update"
    fp_latest = open(update_file, "wb+")  
    for line in fp:
        if line.find("DATA1") == -1:
            fp_latest.write(line)
        if line.find("DATA1") != -1:
            line = line.split()
            pin_name = find_pin_order(line[1])
            update_line = "DATA " + line[1] + " " + pin_name
            fp_latest.write(update_line)
            line = ''.join(line) 
         if line.find("DATA2") != -1:
            line_data = line.split()
            line_data[1] = "TEMP2"
            line_data =' '.join(line_data)
            fp_latest.write(line_data)
         if line.find("DATA3") != -1:
            line_data = line.split()
            line_data[1] = "TEMP3"
            line_data =' '.join(line_data)
            fp_latest.write(line_data)

 fp_latest.close()
 fp.close()
4

2 回答 2

1

The main problem with your current code is that your first if block, which checks for "DATA1" and writes the line out if it is not found runs when "DATA2" or "DATA3" is present. Since those have their own blocks, the line ends up being duplicated in two different forms.

Here's a minimal modification of your loop that should work:

for line in fp:
    if line.find("DATA1") != -1:
        data = line.split()
        pin_name = find_pin_order(data[1])
        line = "DATA " + data[1] + " " + pin_name
    if line.find("DATA2") != -1:
        data = line.split()
        data[1] = "TEMP2"
        line =' '.join(data)
    if line.find("DATA3") != -1:
        data = line.split()
        data[1] = "TEMP3"
        line =' '.join(data)

    fp_latest.write(line)

This ensures that only one line is written because there's only a single write() call in the code. The special cases simply modify the line that is to be written. I'm not sure I understand the modifications you want to have done in those cases, so there may be more bugs there.

One thing that might help would be to make the second and third if statements into elif statements instead. This would ensure that only one of them would be run (though if you know your file will never have multiple DATA entries on a single line, this may not be necessary).

于 2013-04-24T15:39:54.090 回答
1

如果你想在文件中写一个新行替换上次读取的旧内容,你可以使用 file.seek() 方法来移动文件,有一个例子。

with open("myFile.txt", "r+") as f:
    offset = 0
    lines = f.readlines()
    for oldLine in lines:
            ... calculate the new line value ...
            f.seek(offset)
            f.write(newLine)
            offset += len(newLine)
            f.seek(offset)
于 2013-04-24T15:45:36.027 回答