0

I have a file with text like below. I need to remove anything between "AS" and "$$" but keep those 2 words. The replacement should be for the same line and I dont need to check for multi lines as AS and $$ always are in the same line

AS '-1', $$ 
Some extra lines 1
some extra lines 2
AS '24:-1', $$ 
Some extra lines 3
some extra lines 4
AS 'abc-1', $$ 
Some extra lines 5
some extra lines 6

The output should be

AS $$ 
Some extra lines 1
some extra lines 2
AS $$ 
Some extra lines 3
some extra lines 4
AS $$ 
Some extra lines 5
some extra lines 6

3 Answers 3

1

You can read the lines and store them in a list:

with open('file.txt', 'r') as f:
    text = [line for line in f]

Then you can check whether the line contains 'AS' and '$$' and if it does you can write out 'AS $$', otherwise you write out the original line:

with open('txt.txt', 'w') as f:
    for t in text:
        if 'AS' in t and '$$' in t:
            f.write('AS $$\n')
        else:
            f.write(t)
Sign up to request clarification or add additional context in comments.

Comments

1

You can read the lines and use split to get the first and last element from each line to determine if you want to write 'AS $$' or the original line in the new file:

with open("test.txt","r") as input_file:
   lines = input_file.readlines()
   with open("out.txt","w") as output_file:
      for line lines:
         line = line.strip() #remove newline character
         values = line.split() #break up line by spaces, so AS '-1', $$ becomes ['AS', '-1,', '$$]
         if values[0] == 'AS' and values[-1] == '$$':
            output_file.write('AS $$\n')
         else:
            output_file.write(line + '\n')

1 Comment

I can have some extra lines as well in between which I need those as well
0

If you don't care for what's between the 2 words you should just read how much lines you have and write "AA $$" for the number of lines x)

No need to complexify the problem !

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.