/tmp/test.txt
AppleScriptを使用して、コンテンツをファイルに書き込もうとしています。
- ファイルが存在しない場合は、作成します。
- 存在する場合は、内容を置き換えたいと考えています。
AppleScript では、新しいファイルを作成するための構文と、既存のファイルに書き込むための構文が異なるため、これは非常に困難です。ファイルが既に存在する場合は削除してから作成することも考えましたが、AppleScript はデフォルトでゴミ箱に移動するため、それもかなり複雑です。
ファイルに書き込もうとしているデータには、多くの特殊文字が含まれている可能性があるため、AppleScriptdo shell script "cat " + data + " > /tmp/txt.txt"
について何も知らないので、実際にはそうしたくありません。escapeshellarg
以下は私がこれまでに持っているものですが、エラーが発生しています:
ファイル「Macintosh HD:private:tmp:test.txt」を型参照にできません。
ここでwrite_to_file
取得したヘルパー関数を改善して、ファイルが存在しない場合にファイルを作成するようにすることで、これを抽象化したいと思います。
my write_to_file("hello", "/tmp/test.txt", false)
on write_to_file(this_data, target_file, append_data)
try
if not (exists POSIX file target_file) then
make new document file at ("/tmp/" as POSIX file as alias) with properties {name:"test.txt", text:the_data}
end if
set the target_file to the target_file as POSIX file
set the open_target_file to open for access file target_file with write permission
if append_data is false then set eof of the open_target_file to 0
write this_data to the open_target_file starting at eof
close access the open_target_file
return true
on error e
try
display dialog e
close access file target_file
end try
return false
end try
end write_to_file