- 论坛徽章:
- 0
|
怎样实现下面这段代码,一边print,一边写入文件?(想过用读取写入文件的方法,但想到如果需获取的邮件数特别大,不停的读写关闭文件,对硬盘来说,来不可想像了)
- #mail.py
- #!/usr/bin/env python
- import poplib, getpass, string, sys, pickle
- host = raw_input("the hostname:")
- if (len(host)) == 0:
- host = 'your host name'
- username = 'your username'
- password = 'your password'
- else:
- username = raw_input("your username:")
- password = getpass.getpass()
- try:
- sess = poplib.POP3(host)
- sess.user(username)
- sess.pass_(password)
- except:
- print "0^0,there is an error in open connection"
- sys.exit()
- nMess = sess.stat()[0]
- headers = []
- for i in range(1,nMess+1):
- print
- mesg = sess.top(i,0)
- print i, mesg[0]
- for j in range(len(mesg[1])):
- if mesg[1][j][0:5] == 'From:' or mesg[1][j][0:5] == 'Date:':
- print mesg[1][j]
- headers.append(mesg[1][j])
- if nMess>0:
- print "received %i message total"%(nMess)
- d01 = open("From_dizhi.txt", 'w')
- pickle.dump(headers, d01)
- d01.close()
- else:
- print "Nop ,no mail on", host, "for", username
- sess.quit()
复制代码 |
|