2014-01-15 33 views
-1

我有這個簡單的腳本,它將一個文本文件附加到Python中的電子郵件中。當我在IDLE中運行這個腳本時,它工作正常。當我在林冠快速運行然而,我得到這個錯誤:(該文件──test.txt文件在同一目錄中python腳本)Canopy中的Python錯誤,但沒有IDLE

--------------------------------------------------------------------------- 
IOError         Traceback (most recent call last) 
C:\Program Files (x86)\Enthought\Canopy32\App\appdata\canopy-1.2.0.1610.win-x86\lib\site-packages\IPython\utils\py3compat.pyc in execfile(fname, glob, loc) 
    195    else: 
    196     filename = fname 
--> 197    exec compile(scripttext, filename, 'exec') in glob, loc 
    198  else: 
    199   def execfile(fname, *where): 

C:\Users\499293\Desktop\Project Folder\attachex.py in <module>() 
     7 
     8 # Read a file and encode it into base64 format 
----> 9 fo = open(filename, "rb") 
    10 filecontent = fo.read() 
    11 encodedcontent = base64.b64encode(filecontent) # base64 

IOError: [Errno 2] No such file or directory: 'text.txt' 

這是我使用的代碼:

#!/usr/bin/python 

import smtplib 
import base64 

filename = "text.txt" 

# Read a file and encode it into base64 format 
fo = open(filename, "rb") 
filecontent = fo.read() 
encodedcontent = base64.b64encode(filecontent) # base64 

sender = '[email protected]' 
reciever = '[email protected]' 

marker = "AUNIQUEMARKER" 

body =""" 
This is a test email to send an attachement. 
""" 
# Define the main headers. 
part1 = """From: From Person <[email protected]> 
To: To Person <[email protected]> 
Subject: Sending Attachement 
MIME-Version: 1.0 
Content-Type: multipart/mixed; boundary=%s 
--%s 
""" % (marker, marker) 

# Define the message action 
part2 = """Content-Type: text/plain 
Content-Transfer-Encoding:8bit 

%s 
--%s 
""" % (body,marker) 

# Define the attachment section 
part3 = """Content-Type: multipart/mixed; name=\"%s\" 
Content-Transfer-Encoding:base64 
Content-Disposition: attachment; filename=%s 

%s 
--%s-- 
""" %(filename, filename, encodedcontent, marker) 
message = part1 + part2 + part3 

try: 
    smtpObj = smtplib.SMTP('mailhost.work.com', 25) 
    smtpObj.sendmail(sender, reciever, message) 
    print "Successfully sent email" 
except Exception: 
    print "Error: unable to send email" 

我真的不明白錯誤的含義或者爲什麼我使用Canopy而不是IDLE。 (我剛剛下載雨棚採取內置的matplotlib和numpy的優勢)

+0

不允許您將文本文件拖放到程序中嗎?我記得左邊有一個可用的項目/變量列表。 –

+0

@EdgarAroutiounian它有一個文件瀏覽器,我可以拖動文件進行編輯。 – diggers3

回答

3

該文件在同一目錄下的事實是不相關的 - 它必須是在當前工作目錄 - 督察的目錄你'在啓動腳本時仍在使用。否則,您需要將文件的路徑作爲參數傳遞,或者從腳本的位置計算路徑(可從__file__魔術變量中獲取該路徑)。

0

布魯諾說了些什麼。

另外:

在雨棚的Python的面板的右上方是一個下拉菜單。您可以使用它來設置當前工作目錄以匹配您的Python文件的目錄(或者實際上始終同步到打開的python文件的目錄)。這對於你的代碼所做的假設來說是一個簡單的解決方法。

此功能對初學者很有用,但通常不是經驗豐富的開發人員需要的。