Email scraper: saving text to text file

时间:2016-03-04 18:13:45

标签: python variables io

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 个答案:

答案 0 :(得分:1)

问题是input()只会读到第一个新行字符。如果要读取多行,则需要将input()放在循环中。那么问题就是你怎么知道何时突破循环?一个简单的解决方案是寻找输入流完成的标志,例如字符串" EOF"。例如:

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!

然后,您将运行脚本,粘贴电子邮件,然后键入" EOF"。