1

如果我有这样的文本文件:

[001]This is line 1.
[002][too long]This is line 2 but it's Tooooo
oooo long!
[003]This is line 3.

我写了一个'for line in fileA'来读取这个文件,比如:

for line in fileA:
    ...

现在我需要在 line.find("[too long]")>=0 时合并当前行和下一行。我应该怎么做?

PS:我写道:

for line in fileA:
    if line.find("[too long]")>=0:
        loc = fileA.tell()
        fileB = open("file.txt") #open this file again
        fileB.seek(loc)
        line += fileB.readline().strip()

但它没有用。为什么?

4

3 回答 3

3

额外读取文件听起来开销太大。试试这个:

with open('file.txt') as f:
    for line in f:
        if '[too long]' in line:
            line = line.rstrip('\r\n') + next(f)
        print line

印刷

[001]This is line 1.

[002][too long]This is line 2 but it's Tooooooooo long!

[003]This is line 3.

如果在一行[too long]中找到,则会附加以下行。也许您想追加所有其他行,直到一行以[xxx]?

于 2013-01-02T12:10:23.747 回答
2

您可以使用列表推导将所有行添加到列表中,执行与 eumiros 答案非常相似的操作。

with open('file.txt') as f:
    lines = [line.rstrip('\r\n') + next(f) if '[too long]' in line else line for line in f]

然后输出是:

>>> lines
    ['[001]This is line 1.\n', "[002][too long]This is line 2 but it's Tooooooooo long!\n", '[003]This is line 3.\n']
于 2013-01-02T12:26:41.947 回答
0

我不确定实际文件的样子,但我可能会使用这样的东西

contents = """[001]This is line 1.
[002][too long]This is line 2 but it's Tooooo
oooo long!
[003]This is line 3.
"""

lines = iter( contents.split("\n") )

def fix_file( lines ):
    prev = ''
    number = 1
    for line in lines:
        if not line.startswith( '[{0:03d}]'.format( number ) ):
            prev += line
        else:
            yield prev
            number = number + 1
            prev = line
    yield prev

for line in fix_file( lines ):
    print line

这样你就不需要额外的内容了。

于 2013-01-02T12:22:40.140 回答