0

This is a sample input file:

abcd
efgh
#^& 
abcd
efgh

This is the required output for the file:

#^& (#these symbols must be part of the output file)
abcd
efgh

How can I delete all the lines before the special characters without affecting identical/near identical lines that come after? I have about 500 files in which I need this to be done.

I'm a beginner and this is how far I've gotten:

myfile = open("3Attrimmed.txt", "rt") #opens the file
#readfile = myfile.read() #reads the file
lines = myfile.readlines()
finaltxt = ("finaltxt.txt", "w+")

for line in lines:
    if ">" not in line:
        line.strip() #removes the line
    else:
        print line
        break
Anurag N. Sharma
  • 362
  • 2
  • 10
  • Just to clarify, you don't want to filter the matching line itself, but everything that precedes it, right? If so, that's really not what your code does, and your title is misleading. It would be good to edit your title and question to be consistent and make it clear what you need. – joanis Aug 09 '19 at 14:10

1 Answers1

0

This is one approach using a simple iteration.

Ex:

import string

specialChars = set(string.punctuation)
towrite = False
with open("3Attrimmed.txt", "rt") as infile, open("finaltxt.txt", "w+") as finaltxt:
    for line in infile:
        if any(char in line for char in specialChars):   #Check if line has special chars.
            towrite = True
        if towrite:
            finaltxt.write(line)               #Write to output file
Rakesh
  • 81,458
  • 17
  • 76
  • 113