[Tutor] Help with printing to text file
Steven D'Aprano
steve at pearwood.info
Mon Feb 1 19:45:32 EST 2016
On Mon, Feb 01, 2016 at 08:41:31PM +0000, Alan Gauld wrote:
> On 01/02/16 14:07, Chelsea G wrote:
> > Hi,
> >
> > So I am trying to get my function search to print in a text file, but I
> > can only get it to print to Powershell. I have tried several things to get
> > it to print in its own text file but nothing I have tried is working. Can
> > someone tell me what I am doing wrong?
> That's because print sends its output to the standard out.
> You need to store your results somewhere (maybe in a list?) and
> then write() those results to a file.
You don't even need to do that! print has a secret (well, not really a
secret, but you would be amazed how few people know about it) option to
print directly to an open file.
In Python 3 you write:
print("Hello World!", file=output_file)
but in Python 2 you must use this ugly syntax instead:
print >>output_file, "Hello World!"
output_file must be already opened for writing, of course.
So Chelsea's class would become something like this:
class dictionary:
...
def search(self, filename):
with open('weekly_test.csv', 'r') as searchfile, open('testdoc.txt', 'w') as text_file:
for line in searchfile:
if 'PBI 43125' in line:
print >>text_file, line
By the way, the argument "filename" is not used here. Is that
intentional?
But perhaps an even better solution is to use the environment's file
redirection. Powershell should understand > to mean "print to a file",
so you can write:
python myscript.py
to have myscript print output directly to the terminal window, and then:
python myscript.py > testdoc.txt
to redirect the output and write it to testdoc.txt instead.
--
Steve
More information about the Tutor
mailing list