[Tutor] Help with printing to text file

Cameron Simpson cs at zip.com.au
Mon Feb 1 18:28:58 EST 2016

On 01Feb2016 20:41, ALAN GAULD <alan.gauld at btinternet.com> wrote:
>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?
>> 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.

Or, of course, open the file and tell print to write there:

  with open('weekly_test.csv', 'r') as searchfile:
    with open('testdoc.txt', 'w') as text_file:
        print(line, file=text_file)

It looks like you're using python 2. To use the modern print syntax above you 

  from __future__ import print_function

at the top of your python program. Python 3 uses the "function" form of print, 
and you need the above to tell python 2 to do so.

One advantage of Alan's "put it in a list" approach is that you could separate 
the seaching of the CSV into one function returning a list, and then do 
whatever you want (eg print it to your file) as a wholy separate operation.

Cameron Simpson <cs at zip.com.au>

More information about the Tutor mailing list