-1

first of all, completely new to python, so this question might be easy.

I want to read a text file and save it as a new file, separate the header in emails from the body. The place where the header ends is the empty line under "X-UID: 81" (as seen in the image). Not all emails have the "X-UID:" so the empty line is the place where I want to separate it. Is there an easy way to do this?

My code currently looks like this:

with open("1.txt") as fReader:
 corpus = fReader.read()

loc = corpus.find("X-UID")
print(corpus[:loc]) 
  • This sort of works, but I can't separate at the empty line. And don't know how to save as new file

Example email

1 Answers1

-1

One way to do this is to read the entire file as one string, and split it by X-UID: 81 (provided that this substring is present, of course), like so:

parts = s.split('X-UID: 81')
header, body = parts[0], parts[1]

If the file doesn't contain X-UID: 81, you could just split() by double newline (\n\n) with maxsplit=1 to make sure it doesn't split further on the newlines in the email body:

parts = s.split('\n\n', maxsplit=1)
header, body = parts[0], parts[1]
Anton Shpigunov
  • 184
  • 2
  • 8