[Tutor] Help with printing to text file

Alan Gauld alan.gauld at btinternet.com
Mon Feb 1 15:41:31 EST 2016

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?

> class dictionary:
> 	...		
> 	def search(self, filename):
> 		with open('weekly_test.csv', 'r') as searchfile:
> 			for line in searchfile:
> 				if 'PBI 43125' in line:
> 					print line
> 		with open('testdoc.txt', 'w') as text_file
> 			text_file = searchfile

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.

Note that searchfile is only open within the first 'with' section,
it is automatically closed when you leave the with block.
So assigning searchfile to textfile is never going top work.
Even if it did, searchfile is read-only so you couldn't write to it.

So to make it work you need to

1) replace the print line with a line that appends the result
   to a list.

2) replace the textfile assignment with a loop that writes
   each entry in your list to textfile. (You may need to
   append a newline \n at the end of each 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