1

我有一个文件终止,</END>文件可能在</END>. 我不关心空行。但最后一个非空白词是</END>. 我需要在</END>. 我已经做到了fileinput

for each_line in fileinput.input("testme",inplace=True):
    if each_line.strip() == '</END>':
        print "\nAdding ^.*"+source_resource+".*$ \\"
        print destination+" [R="+http_code+",L]"
    print each_line,

请一些专家建议如何使用seek. 我相信seek光标定位非常方便。

4

2 回答 2

1

您有两种可能的方法,一种使用就地写入,另一种意味着创建文件的副本。

第二种方法很容易实现:

with open(src_path, "r") as in_f, open(dest_path, "w") as out_f:
    for line in in_f:
        if line == "</END>":
            out_f.write("whatever you want")
        out_f.write(line)
        out_f.write('\n')

对于第一种方法,我们需要检测结束线并返回其开头:

last = 0
with open(src_path, "r+") as f:
    for line in f:
        if line == "</END>":
            f.seek(last)
            f.write("whatever you want"
            f.write(line) # rewrite the line
            f.write('\n')
        last = f.tell() # This will give us the end of the last line

我确实写了这段代码,所以可能会有一些错误,但你明白了。

于 2013-06-12T11:23:53.540 回答
0

I wouldn't do it with seek, since there you have to specify all the offsets yourself - it forces you to explicitly split lines and the like (depending on the OS ...) - all things that tend to be error-prone.

If your grammar prescribes that each -tag is in a separate line, you can use the code you have (it's simple, understandable and presumably fast).

If you need a less strict syntax, then I would build an easy parser with pyparsing (assuming that performance is not the main concern).

于 2013-06-12T11:26:54.657 回答