2013-03-04 44 views
1

我試圖在已創建的TextEdit文件中編寫。 該文件處於rwxrwxrwx模式,因此沒有權限問題。AppleScript:試圖在TextEdit文件中編寫

但是,當我執行我的代碼,這裏是錯誤:

error "Network file permission error." number -5000 from file "/Users/me/Desktop/A directory/file.txt" to «class fsrf» 

我的代碼在這裏:

-- Writing in the TextEdit file 
set file_URLs_content to "HEEEELLOOOOOO" 
tell application "TextEdit" 
    set theFile to "/Users/me/Desktop/A directory/file.txt" 
    set file_ref to (open for access file theFile with write permission) 
    set eof file_ref to 0 
    write file_URLs_content to file_ref 
    close access file_ref 
end tell 

我的file.txt的仍然是空的,我如何才能避免這個錯誤?

回答

1

你不需要TextEdit。試試這個:

set the logFile to ((path to desktop) as text) & "log.txt" 
set the logText to "This is a text that should be written into the file" 
try 
    open for access file the logFile with write permission 
    write (logText & return) to file the logFile starting at eof 
    close access file the logFile 
on error 
    try 
     close access file the logFile 
    end try 
end try 
1

嘗試:

set file_URLs_content to "HEEEELLOOOOOO" 
set filePath to POSIX path of (path to desktop as text) & "file.txt" 
do shell script "echo " & quoted form of file_URLs_content & " > " & quoted form of filePath 
2

寫有文字編輯文本時,你能避免錯誤的方法是要記住,這是一個文本編輯器。它已經知道如何創建和保存文本文檔而不會產生錯誤。您不必使用(容易出錯)開放訪問。您不必使用(容易出錯)的shell腳本。你所要做的就是要求TextEdit爲你製作一個文本文件,無論你喜歡什麼樣的內容,並保存在任何你喜歡的地方。文本編輯知道如何做到這一點,而不會產生文件訪問錯誤(如打開以訪問)或意外覆蓋的文件夾(如shell腳本。)

tell application "TextEdit" 
    activate 
    set theDesktopPath to the path to the desktop folder as text 
    set file_URLs_content to "HEEEELLOOOOOO" 
    make new document with properties {text:file_URLs_content} 
    save document 1 in file (theDesktopPath & "file.txt") 
    close document 1 
end tell 

這種方法的優點是它更快,更容易編寫,它是不太容易出錯,作爲輸出獲得的文本文件具有與使用TextEdit手動創建的文本文件相同的屬性,並且您的腳本現在可以輕鬆擴展以包含其他應用程序。例如,文本內容可能來自另一個應用程序或剪貼板,並且文本文件可能會在另一個應用程序中打開,或者在保存後通過電子郵件發送。

AppleScript最基本的功能就是以這種方式將消息發送到Mac應用程序。如果要將PNG轉換爲JPEG格式,則不要在AppleScript中編寫PNG解碼器和JPEG編碼器,並打開用於訪問的PNG文件並逐字節地讀取它,然後逐字節地對JPEG進行編碼。您只需讓Photoshop打開PNG圖像並將其以JPEG格式導出到特定的文件位置即可。 「打開訪問」命令是讀取和寫入文件的最後手段,您根本沒有應用程序讀取或寫入。 「do shell腳本」命令用於包含命令行應用程序,當你沒有Mac應用程序來完成這項工作時,例如,你可以用Perl做正則表達式。如果您所做的只是處理文本文件,那麼您不僅可以使用TextEdit,還可以從Mac App Store獲得免費的TextWrangler,並且它具有用於讀取,編寫和編輯文本文件的巨大AppleScript字典。