简体   繁体   English

使用python从文件的特定部分复制到另一部分

[英]Copying from a specific part of a file to another with python

I am trying to copy a specific part of a file to another one. 我正在尝试将文件的特定部分复制到另一部分。 The input file has four lines which start by the same name ("1" in the example given). 输入文件有四行以相同的名称开头(在给定的示例中为“ 1”)。 I don't know exactly how I could take only the part of the file that is between the first "1" and the second "1" (more than 100 lines...): 我不完全知道如何只取文件中第一个“ 1”和第二个“ 1”(超过100行...)之间的部分:

· · 1 · · · 1 · · · 1 ··1···1···1

I just started the following: 我刚刚开始以下工作:

f_read = open(pathway, "r")
f_write = open(pathway, "w")
cnt = 0

with f_read as f1:
    for line in f1:
       if line.startswith("1"):
          cnt =+ 1
          if cnt == 2:
             break

And here I do not know how to specify the part of the file I want (from the first "1" until the second "1")... 而且这里我不知道如何指定我想要的文件部分(从第一个“ 1”到第二个“ 1”)...

Any ideas? 有任何想法吗? Thank you in advance!! 先感谢您!!

Basically, 基本上,

for line in in_file:
   if line.startswith('1'):
       break

for line in in_file:
   if line.startswith('1'):
       break
    <do stuff>

This uses the fact that python iterators are stateful, and the second loop starts where the first one has stopped, not from the beginning. 这利用了python迭代器是有状态的事实,并且第二个循环从第一个循环停止的地方开始,而不是从头开始。

You should use with to open both files. 您应该使用with打开两个文件。 In your code if pathway is actually the same file you immediately open pathway to write after opening it to read so you are basically going to try to iterate over an empty file. 在你的代码,如果路径实际上是同一个文件,你立即打开pathway打开它来读取,所以你基本上要尝试遍历一个空文件后写的。 You should use a temporary file to write to and then update the original if required. 您应该使用临时文件进行写入,然后根据需要更新原始文件。

with open(pathway) as f_read, open("temp_out.txt", "w") as f_write:
    for line in f_read:
         if line.startswith("1")
             for wanted_line in f_read:
                 # work on wanted lines
                 if wanted_line.startswith("1"):
                     break
with open("temp_out.txt", "w") as f_in, open(pathway, "w") as f_out:
    for line in f_in:
        f_out.write(line)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM