将输入文件修改为所需的输出文件

时间:2019-05-30 09:44:01

标签: python-3.x

我有一个输入文件。我要修改输入文件,如下所示:-

输入文件:-

foo bar flower

dragon smile

friends few are there. Here it is

...

..

..

.

foo bar flower

beauty good

ugly bad

...

..

.

我的输出Fie:-

foo bar flower

dragon smile

friends few are there. Here it is

...

..

..

.

//foo bar flower

//beauty good

//ugly bad

//...

//..

//.Rest of the file

我想回头。但是无法弄清楚。

从上次出现的foo bar到文件中的EOF,我需要在输出前加上'//'

1 个答案:

答案 0 :(得分:0)

如果文件不是太大,您可以将其行读入列表中,然后进行处理,以进行回顾和转发所需次数。

这是一个示例,请告诉我这是否适合您(请注意,input.txt应该用您的真实文件名替换):


content = []
with open('input.txt') as f:
    content = f.readlines()

# we find the last index by finding the first occurrence in the reversed list, then subtracting it from the list length
last_foobar_index = len(content) - 1 - content[::-1].index('foo bar flower\n')

# now we go over each line from that index and add leading "//"
for i in range(last_foobar_index,len(content)):
    content[i] = "//"+content[i]

# now just write it to an output file
with open('output.txt', 'w+') as f:
    f.writelines(content)

编辑-因为文件确实很大

由于文件太大,无法容纳在内存中,因此我们希望以一种内存有效的方式来迭代文件,如Methods of File Objects中所述。

我们将对该文件进行2次传递,在第一个文件中,我们将找到最新foo bar的索引,在第二个文件中,我们将创建output.txt:


latest_foobar_index = 0

with open('input.txt') as f:
    for i, line in enumerate(f):
        if line.startswith('foo bar'):
            latest_foobar_index = i

    f.seek(0) # go back to the start of the file

    with open('output.txt', 'w+') as out:   
        for i, line in enumerate(f):
            if i >= latest_foobar_index:
                out.write('//')
            out.write(line)