Python循环并将打印输出附加到电子邮件的变量

Python循环并将打印输出附加到电子邮件的变量,python,Python,我对Python还很陌生,我正在使用Python-2.7.3,在搜索完之后,我想我应该问问社区 我试图将每次迭代基本上捕获到一个变量,这样我就可以将该变量用作电子邮件的正文。我不想写一个文件,然后用它作为我的身体 我尝试过这个,但运气不好: for sourceFile in sortedSourceFiles: print "Checking '%s' " % sourceFile += MsgBody 以下是我运行它时得到的结果: File "check_fil

我对Python还很陌生,我正在使用Python-2.7.3,在搜索完之后,我想我应该问问社区

我试图将每次迭代基本上捕获到一个变量,这样我就可以将该变量用作电子邮件的正文。我不想写一个文件,然后用它作为我的身体

我尝试过这个,但运气不好:

    for sourceFile in sortedSourceFiles:
        print "Checking '%s' " % sourceFile += MsgBody
以下是我运行它时得到的结果:

  File "check_files_alert.py", line 76
    print "Checking '%s' " % sourceFile += MsgBody
                                         ^
SyntaxError: invalid syntax
很抱歉问你这个新手问题。

谢谢

您希望执行以下操作:

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

您以前的代码将其转换为字符串,然后尝试添加到其中。

我真的不确定您在这里要做什么。如果要保留变量,为什么要使用
print

如果只想连接
MsgBody
中的行,则应执行以下操作:

for sourceFile in sortedSourceFiles:
    MsgBody += "Checking '%s' \n" % sourceFile 
或者更好:

MsgBody = '\n'.join("Checking '%s'" % sourceFile for sourceFile in sortedSourceFiles)

问题不清楚。您可以捕获标准输出,也可以打印然后追加或只是追加。我会为这三个负责

如果您有一个函数可以打印,但不希望打印,而是将其打印输出放入列表中,那么您要做的就是捕获
stdout
流。看看如何做

如果您想打印然后附加,那么您可以这样做

for sourcefile in sortedsourcefiles:
    MsgBody += sourceFile
    print "Checking %s" % MsgBody
如果您只想附加它,那么这就足够了

for sourcefile in sortedsourcefiles:
    MsgBody += sourceFile
希望这有帮助。如果您有任何疑问,请询问

for sourcefile in sortedsourcefiles:
    MsgBody += sourceFile