-1

I already have a code that extracts the subject line of a letter from a txt file:

import os
ans = []

for filename in os.listdir(os.getcwd()):
   with open(os.path.join(os.getcwd(), filename), 'r') as rf:
    for line in rf:
        line = line.strip()
        if line.startswith("subject"):
            ans.append(line)
        elif line.startswith("Subject"):
           ans.append(line)
    
with open('extracted_data.txt', 'w') as wf:
    for line in ans:
        wf.write(line)

However, it gets formatted like this:

subject: Block 8 of EricssonSubject: Block 9 of Ericssonsubject: Block 10 of Ericssonsubject: Block 11 of Ericsson

When I want it to look like this:

subject: Block 8 of Ericsson
Subject: Block 9 of Ericsson
subject: Block 10 of Ericsson
subject: Block 11 of Ericsson

How do I get it to format in the above desired way?

petezurich
  • 9,280
  • 9
  • 43
  • 57
  • 2
    `wf.write(line + '\n')` – John Gordon Jul 11 '22 at 05:16
  • Does this answer your question? [How to read a file line-by-line into a list?](https://stackoverflow.com/questions/3277503/how-to-read-a-file-line-by-line-into-a-list) – ntg Jul 11 '22 at 05:37

1 Answers1

1

replace

with open('extracted_data.txt', 'w') as wf:
    for line in ans:
        wf.write(line)

to

with open('extracted_data.txt', 'w') as wf:
    for line in ans:
        wf.write(line+'\n')
ElapsedSoul
  • 725
  • 6
  • 18