【问题标题】:How do I copy part of a file to a new file?如何将文件的一部分复制到新文件?
【发布时间】:2018-09-17 17:52:16
【问题描述】:

在 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)

【问题讨论】:

  • 您可以使用 split('\n') 返回每行的列表,然后使用正则表达式模式删除符合给定模式的行

标签: python-3.x text readline


【解决方案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)

【讨论】:

    【解决方案2】:

    阅读每一行并注意它是否包含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)
    

    【讨论】:

      猜你喜欢
      • 2016-06-11
      • 1970-01-01
      • 1970-01-01
      • 2020-12-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-08
      • 2011-12-29
      相关资源
      最近更新 更多