dポイントプレゼントキャンペーン実施中!

Applescriptを始めたばかりの初心者です。

テキストファイルを読み込んで、検索置換を行うスクリプトを作成してます。
検索置換まではなんとかできたのですが、ファイルを同じ場所に同じ名前で上書きしたいのですが、うまくいきません。見よう見まねで作成しているので、エラーがでても対処できませんでした。
どうかアドバイスをお願いします。


set thefile to "■■HD:0000:0000.txt"--いつも同じファイルを読み込む

try
set fn to open for access file thefile with write permission
set mystr to read fn -- 全ての内容を得る
end try

display dialog mystr--内容の確認



set mystr to my replaceAll(mystr, "▼", return)
display dialog mystr--内容の確認
write mystr to fn
close access fn


on replaceAll(motoStr, findStr, repStr)
set OriginalDelimiters to AppleScript's text item delimiters
set AppleScript's text item delimiters to {findStr}
set motoStr to text items of motoStr
set AppleScript's text item delimiters to {repStr}
set motoStr to motoStr as string
set AppleScript's text item delimiters to OriginalDelimiters
return motoStr
end replaceAll

A 回答 (1件)

read、writeするとき、かならず読み書きを失敗したときの処理を行うようにしてください。


おそらくうまくいかないのは、エラーが起きて失敗したあとに再度試行するときに、ファイルが閉じられていないからだと思われます。エラーが起きても、ファイルを閉じるようにします。

読み込み:
try
set fn to open for access file thefile with write permission
set mystr to read fn -- 全ての内容を得る
on error
close access fn
return
end try
書き込み:
try
write mystr to fn
on error
close access fn
return
end try
close access fn

また、readでは、どこまで読み込むか明示しないと、うまく読み込めないようです。
set mystr to read fn for (get eof fn) -- 最初からEOFまで読み込む

writeでは、置換前の文字数より、置換後の文字数が減った場合、最後に置換前のゴミが残ってしまうので、EOFを書き込むようにしましょう。

write mystr to fn
set eof fn to (length of mystr + 1)

この回答への補足

最初うまくいかずいろいろ試したところ
下記の部分を
write mystr to fn
set eof fn to (length of mystr + 1)
修正後
set eof fn to 0
write mystr to fn

としたところうまく動作しました。

harawoさんありがとうございました。

補足日時:2011/06/07 17:25
    • good
    • 0
この回答へのお礼

こんなに早く回答していただいてびっくりしました。
とても親切に教えて頂いてありがとうございます。
早速試してみます。

お礼日時:2011/06/07 08:22

お探しのQ&Aが見つからない時は、教えて!gooで質問しましょう!