You could make a function which prints both to console and to file. You can either do it by switching stdout, e.g. like this:
def print_both(file, *args):
temp = sys.stdout #assign console output to a variable
print ' '.join([str(arg) for arg in args])
sys.stdout = file
print ' '.join([str(arg) for arg in args])
sys.stdout = temp #set stdout back to console output
or by using file write method (I suggest using this unless you have to use stdout)
def print_both(file, *args):
toprint = ' '.join([str(arg) for arg in args])
print toprint
file.write(toprint)
Note that:
- The file argument passed to the function must be opened outside of the function (e.g. at the beginning of the program) and closed outside of the function (e.g. at the end of the program). You should open it in append mode.
- Passing *args to the function allows you to pass arguments the same way you do to a print function. So you pass arguments to print...
...like this:
print_both(open_file_variable, 'pass arguments as if it is', 'print!', 1, '!')
Otherwise, you'd have to turn everything into a single argument i.e. a single string. It would look like this:
print_both(open_file_variable, 'you should concatenate'+str(4334654)+'arguments together')
I still suggest you learn to use classes properly, you'd benefit from that very much. Hope this helps.