BUKTOP
BUKTOP

Reputation: 980

Applescript: read text from file

I can't read text from text file using applescript. Tried this:

set sharesFileName to (the POSIX path of (path to home folder)) & "Applications/mounts"
set sharesLines to paragraphs of (read POSIX file sharesFileName as "class utf8" using delimiter linefeed)

Got "Script Error", "End of file error"

What am I doing wrong? File, surely, exists and readable

Upvotes: 3

Views: 4840

Answers (2)

user3439894
user3439894

Reputation: 7555

If mounts is a plain text file, then the following example AppleScript code should work:

set sharesFileName to (the POSIX path of (path to home folder)) & "Applications/mounts"
set sharesLines to read sharesFileName

Example:

$ cat mounts
one
two
three
$

Using:

set sharesLines to read sharesFileName

Results:

"one
two
three
"

Using:

set sharesLines to read sharesFileName using delimiter linefeed

Results:

{"one", "two", "three"}

Using:

set sharesLines to paragraphs of (read sharesFileName)

Results:

{"one", "two", "three", ""}

As you can see the last example includes the last linefeed as an empty string in the file, where using using delimiter linefeed does not, and both create a list. So if you want sharesLines to be as list, then use:

set sharesLines to read sharesFileName using delimiter linefeed

If you want sharesLines to just contain the contents of mounts as paragraphs of text, then use:

set sharesLines to read sharesFileName

Note: The example AppleScript code is just that and does not employ any error handling and is meant only to show one of many ways accomplish a task. The onus is always upon the User to add/use appropriate error handling as needed/wanted.

Upvotes: 4

wch1zpink
wch1zpink

Reputation: 3142

This works for me using the latest version of Sierra(After reading your comment it was only a simple text file)

set sharesFileName to (the POSIX path of (path to home folder)) & "Applications/mounts.txt"
set sharesLines to paragraphs of (read sharesFileName)

Upvotes: 0

Related Questions