My simple script parse output screen and to a new file!

chuck amadi chuck.amadi at ntlworld.com
Thu Jun 10 01:00:45 CEST 2004


Hi again I've bee tryinh to get print statement output from the screen 
to a new file.
Im using the for loop I assume my target can and is a reference variable 
and my object is  mbox.
I have tried a few variations the script runs ok but when I cat the the 
new file it's empty but I nedd the output to flush to this new file in 
order to utilise and populate a database at some point.
Cheers

Chuck

#!/usr/bin/env python
 
import sys
import os
import email
import mailbox
import StringIO
 
# Open the testwws user mailbox (tmp user chuck)
# fp denotes factory paraemeter
# mode can be 'r' when the file will only be read, 'w' for only writing
#(an existing file with the same name will be erased), and 'a' opens the 
file
# for appending; any data written to the file is automatically added to 
the end.# 'r+' opens the file for both reading and writing. The mode.
 
# The File SurveyResults.txt must all ready exist.
 
#mailout = open("/home/chuck/pythonScript/SurveyResults.txt") # mode 'w' 
means open the file for writ-ing
# (any data already in the file will be erased)
#output.writelines(mailout)
#mailout = file("/home/chuck/pythonScript/SurveyResults.txt")
 
# open() returns a file object, and is most commonly used with two 
arguments:
# "open(filename, mode)".
fp = open("/home/chuck/pythonScript/testbox")
 
# message_from_file returns a message object struct tree from an
# open file object.
 
mbox = mailbox.UnixMailbox(fp, email.message_from_file)
# list of body messages.
bodies = []
 
# mail is the file object
for mail in mbox:
        #print 'mail'
        print mail['Subject']
        print mail.get_content_type()#text/plain
        print mail.get_payload()
 
 
# First open the testbox file to read(r) and write(w)to the 
SurveyResults.txt
# open() has been depreicated use file()
#fp = open("testbox","r")
mailout = file("/home/chuck/pythonScript/SurveyResults.txt","a")
 
# Read the testbox file into a list then copy to
# new file.
#for mail in fp.readlines():
# for <target> in <object>
    for mail in mbox:
    mailout.write(mail)
 
print "testbox file copied...to SurveyResults.txt"
 
# Now close the files
#fp.close()
mailout.close()
 
#mailout.close to close it and free up any system resources taken up by 
the open file.
# After calling output.close(), attempts to use the file object will 
automatically fail.





More information about the Python-list mailing list