On 01Feb2016 20:41, ALAN GAULD <alan.ga...@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
need:
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.
Cheers,
Cameron Simpson <c...@zip.com.au>
_______________________________________________
Tutor maillist - Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor