[Tutor] Help with printing to text file

Alan Gauld alan.gauld at btinternet.com
Mon Feb 1 15:47:46 EST 2016

On 01/02/16 14:07, Chelsea G wrote:

> 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?

I meant to add in my other reply that you could combine the
reading and writing into a single 'with' block and thus avoid
creating the intermediate list. That could save important
memory if searchfile is a big file.

You can open 2 files in a single with statement:

with open('foo.txt','r') as infile, open ('bar.txt','w') as outfile:
    for line in infile:
        if searchstring in line:

Alan G
Author of the Learn to Program web site
Follow my photo-blog on Flickr at:

More information about the Tutor mailing list