Python Print to a File

One day, when I was writing a program that requires a 2D map. All things are well designed and the random map is printed to the console screen. However, I found what I need is not to show my some maps, but to the computer, which to let the computer know about the map's info.

To say more commonly, I need to put the which I print to console to the memory. There are several ways to do this tricky things.

First, I put what my program prints to a file, that is really simple.

import sys
__console__ = sys.stdout()
file = open('file_to_store_print', 'w')
sys.stdout() = file

#now what you print is stored in the file

#don't forget to rewrite the stdout when you don't need it anymore.
sys.stdout() = __console__

#and your file needs to be closed
f.close()

Now, your file is actually a console screen. And if you are familiar with shell, you will find an easier way to do things like this.

python file_to_print.py > file_to_store.txt

This way, we just to use python commander to implement this function. And you could also do things like this.

import os
os.exec('python file_to_print.py > file_to_store.txt')

The first way gains more controller of the things to put, because if you do in the second way, your may have to put the print function in an individual file.

blogroll

social