1

Problem: I have a .txt file with string that looks like this:

Q. Going back to July who all lived with you? 9 A. Ten people. 10 Q. Okay. So for the year, you had ten people living with you? 13 A. Yes.
Q. Going back to July who all lived with you? 9 A. Ten people. 10 Q. Okay. So for the year, you had ten people living with you? 13 A. Yes.
Q. Going back to July who all lived with you? 9 A. Ten people. 10 Q. Okay. So for the year, you had ten people living with you? 13 A. Yes.

What I would like to do: I would like to loop through the entire .txt file and add a '\n' in front of each 'Q.' and 'A.' so that when I reopen the .txt file, each Q. and A. string is on a separate line.

martineau
  • 119,623
  • 25
  • 170
  • 301
Adam
  • 15
  • 4

1 Answers1

1

You can use .replace() to replace each "Q." with "\nQ." (and similar for "A.").

with open("in.txt") as in_file, open("out.txt", "w") as out_file:
    for line in in_file:
        out_file.write(line.replace("A.", "\nA.").replace("Q.", "\nQ."))
BrokenBenchmark
  • 18,126
  • 7
  • 21
  • 33