2017-02-28 22 views
0

我正在嘗試創建一個包含預定文本的applescript的plist文件。我需要能夠將此文本寫入文件「plistfile.plist」,但每當我運行腳本時都會收到錯誤「Can't get file (alias "MacintoshHD:Users:myusername:Desktop:plistfile.plist")」。我的腳本是:腳本錯誤:無法在Applescript中獲取文件?

set plistfilename to POSIX file "/Users/myusername/Desktop/plistfile.plist" as alias 

set ptext to "plist text" 

set plist to open for access file plistfilename & "plistfile.plist" with write permission 
write ptext to plist 
close access file plist 

我不是很熟悉這一點,但我認爲這是有道理的。我做了一些谷歌搜索,並沒有在其他地方發現這個問題。如果有人能讓我知道我錯過了什麼,我會非常感激。

回答

1

代碼失敗,因爲如果文件不存在,強制as alias會引發錯誤。

這是寫文本文件通常的和可靠的方式

set plistfilename to (path to desktop as text) & "plistfile.plist" 

set ptext to "plist text" 

try 
    set fileDescriptor to open for access file plistfilename with write permission 
    write ptext to fileDescriptor as «class utf8» 
    close access fileDescriptor 
on error 
    try 
     close access file plistfilename 
    end try 
end try 

編輯:

認爲腳本的結果是一個簡單的.txt文件,即使你通過.plist延期。

要創建您可以使用真正屬性列表文件System Events

tell application "System Events" 
    set rootDictionary to make new property list item with properties {kind:record} 
    -- create new property list file using the empty dictionary list item as contents 
    set the plistfilename to "~/Desktop/plistfile.plist" 
    set plistFile to ¬ 
     make new property list file with properties {contents:rootDictionary, name:plistfilename} 
    make new property list item at end of property list items of contents of plistFile ¬ 
     with properties {kind:boolean, name:"booleanKey", value:true} 
    make new property list item at end of property list items of contents of plistFile ¬ 
     with properties {kind:string, name:"stringKey", value:"plist text"} 
end tell 

的腳本創建此屬性列表文件:

<?xml version="1.0" encoding="UTF-8"?> 
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> 
<plist version="1.0"> 
<dict> 
    <key>booleanKey</key> 
    <true/> 
    <key>stringKey</key> 
    <string>plist text</string> 
</dict> 
</plist> 
相關問題