Using python to write specific lines from one file to another file

前端 未结 5 1893
攒了一身酷
攒了一身酷 2020-12-05 11:41

I have ~200 short text files (50kb) that all have a similar format. I want to find a line in each of those files that contains a certain string and then write that line plus

5条回答
  •  一个人的身影
    2020-12-05 12:14

    ajon has the right answer, but so long as you are looking for guidance, your solution doesn't take advantage of the high-level constructs that Python can offer. How about:

    searchquery = 'am\n'
    
    with open('Test.txt') as f1:
      with open(Output.txt, 'a') as f2:
    
        Lines = f1.readlines()
    
        try:
          i = Lines.index(searchquery)
          for iline in range(i, i+3):
            f2.write(Lines[iline])
        except:
          print "not in file"
    

    The two "with" statements will automatically close the files at the end, even if an exception happens.

    A still better solution would be to avoid reading in the whole file at once (who knows how big it could be?) and, instead, process line by line, using iteration on a file object:

      with open('Test.txt') as f1:
        with open(Output.txt, 'a') as f2:
          for line in f1:
            if line == searchquery:
              f2.write(line)
              f2.write(f1.next())
              f2.write(f1.next())
    

    All of these assume that there are at least two additional lines beyond your target line.

提交回复
热议问题