2011-07-21 65 views
2

打開文件可在當前工作目錄下的Temp文件夾中的蟒蛇打開文件Python中PWDIR的文件夾,通過AppleScript的

我試圖

pwdir=os.getcwd() 
tempdir=pwdir+"/temp/test.txt" 
f=open(tempdir,'r+') 

當我打印TEMPDIR的路徑,它顯示了正確並且還讀取文件的內容。

當我嘗試從調用此python腳本的Applescript中結合此操作時。我得到這樣

f=open(pwdir1,'r+') 
IOError: [Errno 2] No such file or directory: '//temp/test.txt'" number 1 

編輯錯誤:

我使用shell腳本從AppleScript的調用這個pythonscript

do shell script "/Users/mymac/Documents/'Microsoft User Data'/test.py" 

編輯:

Python代碼:

tempdir = os.path.join(os.getcwd(),'temp','htmlinput.html') 
print tempdir 
with open(tempdir) as f: 
    html=f.read() 

Pyt (輸出完全正常)

/Users/mymac/Documents/Microsoft User Data/Outlook Script Menu Items/temp/htmlinput.html 

我也能夠看到文件內容。

的AppleScript代碼:

do shell script "/Users/mymac/Documents/'Microsoft User Data'/'Outlook Script Menu Items'/new.py" 

AppleScript的錯誤:

error "Microsoft Outlook got an error: Traceback (most recent call last): 
    File \"/Users/mymac/Documents/Microsoft User Data/Outlook Script Menu Items/new.py\", line 12, in <module> 
    with open(tempdir) as f: 
IOError: [Errno 2] No such file or directory: '/temp/htmlinput.html'" number 1 
+0

@eryksun同樣的問題之一..已更新問題 – thinkcool

+0

@eryksun打印錯誤 – thinkcool

+0

嘗試@eryksun建議的或我在編輯中建議的內容。 Eryksun,你需要更頻繁地發佈答案,而不是評論,所以我可以upvote你。 – agf

回答

3

我不知道Applescript - 或OS X的一般。它看起來像是從根文件夾運行腳本,os.getcwd()返回'/'。腳本本身的目錄本身是sys.path[0]或當前模塊的目錄名稱 - dirname(__file__) - 如果它是單個腳本而不是包。請嘗試以下

import os, sys 
tempdir = os.path.join(sys.path[0], 'temp', 'temp.txt') 

import os 
tempdir = os.path.join(os.path.dirname(__file__), 'temp', 'temp.txt') 
1

雙斜線是你的問題。在Python中加入文件和路徑名的正確方法是os.path.join。嘗試:

tempdir = os.path.join(os.getcwd(), 'temp', 'test.txt') 

此外,你應該做:

with open(tempdir) as f: 

這將使即使你有一個錯誤肯定TEMPDIR被關閉。

編輯:

我們需要看到tempdir就是當腳本由AppleScript的,不是當它從終端調用的調用。如果你這樣做

tempdir = os.path.join(os.getcwd(),'temp','htmlinput.html') 
with open('/Users/mymac/Documents/temp.txt', 'w') as fwrite: 
    fwrite.write(tempdir) 

究竟是什麼結果在文件/Users/mymac/Documents/temp.txt

+0

@ agf..Nope同樣的錯誤。它可以單獨在Python中打開,並且在我嘗試使用不同的文件時,在shell腳本中也沒有問題。 – thinkcool

+0

從錯誤消息中看起來像是不只是傳遞它'os.path.join(os。 getcwd(),'temp','test.txt')',否則它不會有額外的雙引號和'數字1'。請嘗試編輯你的帖子以添加'open.path.join(os.getcwd(),'temp','test.txt')'顯示以及當你打開時顯示的錯誤__exactly__(os.path .join(os.getcwd(),'temp','test.txt'))' – agf

+0

打印錯誤 – thinkcool

相關問題