0

I am pretty new to Python, I am using Python-2.7.3, after searching and coming up empty I figured I would ask the community.

I am trying to basically capture each iteration to a variable, so I can use that variable as the body of my email. I do not want to write a file and then use that as my body.

I have tried this with no luck:

    for sourceFile in sortedSourceFiles:
        print "Checking '%s' " % sourceFile += MsgBody

Here is what I get when I run it:

  File "check_files_alert.py", line 76
    print "Checking '%s' " % sourceFile += MsgBody
                                         ^
SyntaxError: invalid syntax

Sorry for the newbie question.
Thanks

jaysunn
  • 87
  • 3
  • 12

4 Answers4

1

The question isn't clear. Either you want to capture the standard output or you want to print and then append or just append. I'll answer for all three.

If you have a function that prints but you don't want it to print but instead put its print output into a list then what you want to do is called capturing the stdout stream. See this question for how to do it.

If you want to print and then append then you can do something like this

for sourcefile in sortedsourcefiles:
    MsgBody += sourceFile
    print "Checking %s" % MsgBody

If you just want to append it then this should be sufficient.

for sourcefile in sortedsourcefiles:
    MsgBody += sourceFile

Hope this helped. If you have any queries ask.

Community
  • 1
  • 1
Aseem Bansal
  • 6,722
  • 13
  • 46
  • 84
0

You would want to do this:

for sourcefile in sortedsourcefiles:
    MsgBody += sourceFile
    print "Checking %s" % MsgBody

Your previous code was turning it into a string, and then trying to add to it.

0

I'm really not sure what you are trying to do here. If you want to keep a variable, why are you using print?

If you just want to concatenate the lines in MsgBody, you should do this:

for sourceFile in sortedSourceFiles:
    MsgBody += "Checking '%s' \n" % sourceFile 

Or even better:

MsgBody = '\n'.join("Checking '%s'" % sourceFile for sourceFile in sortedSourceFiles)
Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
0
for sourceFile in sortedSourceFiles:
  MsgBody += sourceFile
DhruvPathak
  • 42,059
  • 16
  • 116
  • 175