2012-04-08 31 views
5

我試圖創建一個AppleScript,它讀取文本文件並將內容放入列表中。該文件是一個簡單的文本文件,其中每行看起來像這樣:example-"example"將文本文件讀入AppleScript中的列表

第一個是文件名,另一個是文件夾名稱。

這裏是我現在的代碼:

set listOfShows to {} 
set theFile to readFile("/Users/anders/Desktop/test.txt") 
set Shows to read theFile using delimiter return 
repeat with nextLine in Shows 
    if length of nextLine is greater than 0 then 
     copy nextLine to the end of listOfShows 
    end if 
end repeat 
choose from list listOfShows 


on readFile(unixPath) 
    set foo to (open for access (POSIX file unixPath)) 
    set txt to (read foo for (get eof foo)) 
    close access foo 
    return txt 
end readFile 

當我運行的輸出我得到這個:

error "Can not change \"Game.of.Thrones-\\\"Game Of \" to type file." number -1700 from "Game.of.Thrones-\"Game Of " to file" 

我的名單看起來是這樣的:Game.of.Thrones-「權力的遊戲「還有兩條這樣的線。

回答

5

的錯誤是,你嘗試讀取內容的文件(你讀的第一個文件)文件的。獲取段落的文本將在返回/換行邊界處將其分開,這通常比試圖猜測文件中使用的行尾字符(s)更好。

也僅僅閱讀文件時,不需要整個打開以訪問的事情,所以你的腳本可以被減少到只有

set listOfShows to {} 
set Shows to paragraphs of (read POSIX file "/Users/anders/Desktop/test.txt") 
repeat with nextLine in Shows 
    if length of nextLine is greater than 0 then 
     copy nextLine to the end of listOfShows 
    end if 
end repeat 
choose from list listOfShows 
+0

它仍然只能讀取「遊戲在我的輸出中,我沒有得到任何錯誤 – andeersg 2012-04-08 19:11:51

+0

我嘗試了文本:1text,2text ... 5text在文本文件中,結果是1text,2text,3text ,4text,5. Not 5text – andeersg 2012-04-08 19:17:01

+0

腳本只是獲取文件的每一行(用換行符等換行符分隔)並將其放入列表中 - 不是在你問什麼?不知道爲什麼文件不會被完全讀取,除非您沒有使用簡單的讀取命令並且正在使用分隔符或讀取的字符數。 – 2012-04-08 19:40:08

2

read默認使用的MacRoman,所以它攪亂了非除非添加as «class utf8»,否則UTF-8文件中的ASCII字符。 (as Unicode text是UTF-16。)

paragraphs of (read POSIX file "/tmp/test.txt") as «class utf8» 

paragraphs of還與CRLF和CR的行結束。這不,但卻忽略了最後一行,如果它是空的:

read POSIX file "/tmp/test.txt" as «class utf8» using delimiter linefeed 
0

的AppleScript語言參考120頁指出:

一系列字符的任意結束後的第一個字符後,立即開始前一段或文本的開頭,以回車符(\ r),換行符(\ n),回車/換行符對(\ r \ n)或文本結尾結尾。 Unicode「段落分隔符」字符(U + 2029)不受支持。

因此,U + 8232被忽略和AppleScript返回從文件全文...

U + 8232是在文本編輯作爲CR字符...

1
set milefile to ((path to desktop as text) & "Alert.txt") 
set theFileContents to (read file milefile) 
display dialog theFileContents 
+0

儘管此代碼可能回答此問題,但提供 有關_why_和/或_how_的其他上下文,它將回答 該問題將顯着提高其長期值 的值。請[編輯]你的答案,添加一些解釋。 – 2016-04-27 12:10:43