0

Hey I’m trying to write a very simple email scraper in Python 3, that asks the user for text of the emails and saves that to a .txt file.

I tried to aks the user for input and store it in a variable and then appending that variable to a text file. But that only saves the first line of the email to the text file. To me it looks like the variable in which i’m trying to store the email only saves the first line, and stops when it comes across a newline.

This is the code that I tried. But only writes first line to file.txt instead of the whole text. How can I make this work?

print("Paste text from email")
content = input(">")
file = open('file.txt','a')
file.write('\n' + '--new email--' + '\n' + content + "\n")

1 Answers1

1

The problem is that input() will only read until the first new line character. If you want to read multiple lines, you need to put input() in a loop. The problem then becomes how do you know when to break out of the loop? An easy solution would be to look for a flag that the stream of input is done, such as the string "EOF". For example:

print("Paste text from email")

content = ""
line = input(">")
while line != "EOF":
    content += line + "\n"
    line = input(">")

file = open('file.txt','a')
file.write('\n' + '--new email--' + '\n' + content + "\n")
file.close() # don't forget to close your file!

You would then run the script, paste the email, and then type "EOF".

dbc
  • 620
  • 7
  • 19
  • Thanks! That works. Is there a way around having a flag to mark to end of the email? – Niel de Vries Mar 04 '16 at 23:17
  • You could put a timeout on the input, so after nothing is entered for x seconds, write the file. https://stackoverflow.com/questions/15528939/python-3-timed-input – dbc Mar 07 '16 at 21:22