如何将文件的一部分复制到新文件?

时间:2018-04-08 03:40:19

标签: python-3.x text readline

在Python中,我想将文本文件打开为file,并将file的一部分复制到新文件中。例如,我只想复制文件的一部分,例如在行EXAMPLE\n和行END\n之间复制。所以我想删除第EXAMPLE\n行之前的所有内容以及第END\n行之后的所有内容。我怎么能这样做?

我可以使用以下代码读取文件,但如何删除

with open(r'filepath\myfile.txt', 'r') as f:
    file = f.readlines()

<delete unwanted lines in file>

with open(r'filepath\newfile.txt', 'r') as f:
    f.writelines(file)

2 个答案:

答案 0 :(得分:1)

创建一个新数组,只将所需的行添加到该数组中:

new_lines = []
found_example=False
found_end=False
for line in file:
    if line == "EXAMPLE\n": found_example=True
    if line == "END\n": found_end=True
    if found_example != found_end: new_lines.append(line)

file = new_lines

现在只需将文件写入您的文件即可。请注意,在您的示例中,您没有以写入模式打开文件,因此它看起来更像是这样:

with open(r'filepath\newfile.txt', 'w+') as f:
    f.writelines(file)

答案 1 :(得分:1)

读取每一行并注意它是否包含EXAMPLE或END。在前一种情况下,设置一个标志以开始输出行;在后者中,设置相同的标志停止。

process = False
with open('myfile.txt') as f, open('newfile.txt', 'w') as g:
    for line in f:
        if line == 'EXAMPLE\n':
            process = True
        elif line == 'END\n':
            process = False
        else:
            pass
        if process:
            line = line.strip()
            print (line, file=g)