AppleScriptファイルの読み書き方法

このQ&Aのポイント
  • Applescriptを使ってテキストファイルの読み込みと検索置換を行う方法について初心者向けに解説します。
  • 質問者はテキストファイルを読み込み検索置換するApplescriptを作成していますが、ファイルの上書き方法について困っています。
  • エラーが発生しても対処できない質問者のために、ファイルの上書き方法についてアドバイスをお願いします。
回答を見る
  • ベストアンサー

AppleScriptファイルの読み書きについて

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

質問者が選んだベストアンサー

  • ベストアンサー
  • harawo
  • ベストアンサー率58% (3742/6450)
回答No.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)

ADJUSTLIGHT
質問者

お礼

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

ADJUSTLIGHT
質問者

補足

最初うまくいかずいろいろ試したところ 下記の部分を write mystr to fn set eof fn to (length of mystr + 1) 修正後 set eof fn to 0 write mystr to fn としたところうまく動作しました。 harawoさんありがとうございました。

関連するQ&A

  • applescript スクリプトエディタとアプリケーションで実行結果が異なる

    クリップボードの文字列を検索置換しようとしています。 \\hoge\hogehoge→/Volumes/hogehogeのように。 ソースは下記なんですが、スクリプトエディタ上で実行すると 期待された結果が返ってくるのですが、アプリケーションとして 保存し、デスクトップからアプリケーションを実行すると 置換二つ目が処理されず、なぜか置換一つ目しか処理されません。 どのようにしたらよいでしょうか。 set theText to get the clipboard set backslash to ASCII character 128 set searchWd to backslash if (offset in theText of searchWd) = 0 then else set theText to my replaceTxt(theText, backslash, "/") --置換一つ目 set theText to my replaceTxt(theText, "//hoge", "/Volumes") --置換二つ目 display dialog theText end if on replaceTxt(myText, searchTxt, replaceTxt) set oldDel to AppleScript's text item delimiters set AppleScript's text item delimiters to searchTxt set myText to every text item of myText set AppleScript's text item delimiters to replaceTxt set myText to myText as string set AppleScript's text item delimiters to oldDel return myText end replaceTxt

  • AppleScriptでpathを取得

    クリックしたファイルの絶対パスをクリップボードに保存する AppleScript(以下に記載)があるのですが、これでは クリップボードの中身が '/Users/ABC/Desktop/tmp1.jpg' '/Users/ABC/Desktop/tmp2.jpg' となります。 クオーテーション「 ' 」なしで、クリップボードに保存したいのですが どのようにすれば良いのでしょうか。 rest of characters of などを使ってどうにか組もうとしたのですが 初心者にはできませんでした。 どなたか、よろしくお願いします。 tell application "Finder" set theItems to "__OBJ_PATH__" set theResult to "" set old_delims to AppleScript's text item delimiters set AppleScript's text item delimiters to ":" set max to count of (every text item of theItems) repeat with num from 1 to max set theResult to theResult & quoted form of (text item num of theItems) if max > 1 and num < max then set theResult to "theResult" & " " end if end repeat set AppleScript's text item delimiters to old_delims set the clipboard to theResult end tell

  • applescriptでのファイルコピー

    macmini server (SnowLeopard:OSX10.6) 上記機種を使用。 macの知識がなく、最近applescriptという機能を知りました。 使い方が全くわからない状態でしたが、 今回、NAS(マウント済み)にあるフォルダAの中のファイルBを macのServer HDの中にあるフォルダCへコピーする作業を 自動化させたいと思い、ファイルコピーの方法について調べていたところ、 とある質問サイトで下記のコードを見つけ、入力項目を埋めて実行しました。 が、「必要なボリュームがマウントされていません」とエラーがでました。 既にマウントしているのは確認しています。 恐らくボリューム名かファイルパスの入れ方が違うのかなと思い、 いろいろと試してみましたが、出来ませんでした。 ここでいうボリューム名とファイルパスとフォルダパスは どのような入れ方をすればよいのでしょうか? もしくは、他の原因であれば、その解決策を教えて頂けると 助かります。 すみませんが宜しくお願い致します。 ------ ペーストするコード (以下最後まで) -------------------- ----【入力項目】------------ set FromVolumName to "ボリューム名を入れる" ---(↑説明)コピー元となるファイルのあるボリューム名 set ToVolumName to "ボリューム名を入れる" ---(↑説明)コピー先となるフォルダのあるボリューム名 set FromCopyFile to "ファイルパスを入れる" ---(↑説明)コピー元となるファイルのパス set ToCopyFolder to "フォルダパスを入れる" ---(↑説明)コピー先となるフォルダのパス set CP_opt to "-f" ---(↑説明)cpコマンドのオプション ------------------------- tell application "Finder" set {MyMsg, MyIcn} to {"完了!", 1} if (exists disk FromVolumName) and (exists disk ToVolumName) then try do shell script "cp " & CP_opt & " " & quoted form of POSIX path of FromCopyFile & " " & quoted form of POSIX path of ToCopyFolder on error set {MyMsg, MyIcn} to {"なんらかのエラーです!", 0} end try else set {MyMsg, MyIcn} to {"必要なボリュームがマウントされていません!", 0} end if activate display dialog MyMsg buttons {"終了"} default button 1 with icon MyIcn end tell

    • ベストアンサー
    • Mac
  • AppleScriptで

    AppleScriptで jとgはtext変数、 iはinteger変数なんですが、 gのi単語目をjのi単語目に書き換えたいのですが set word i of g to word i of j で行うとエラーになります。 どうすれbくぁいいのでしょうか。

    • 締切済み
    • Mac
  • AppleScriptを使ってXCODE3.2で遊んでますが、ラジオボ

    AppleScriptを使ってXCODE3.2で遊んでますが、ラジオボタンの値を読み出せなくて行き詰まっています。 ポップアップメニューだと set xxx to (abcXyz's titleOfSelectedItem()) as string で読み出せるのですが ラジオボタンは同じ方法では読み出せないのです どうやればいいかお分かりの方よろしくお願いします

    • ベストアンサー
    • Mac
  • AppleScriptエラーで困っています!

    XcodeでAppleScriptを使用してプログラミングしています。 InterfaceBuilderでテキストフィールドを作りそこにテキストを入れるプログラムを以下のように記述しました。 set contents of text field "textfield" of window "main" to abc abcには既にテキストデータを入れています。 これを実行しようとすると A " can't go after this identifier. というエラーが出ます。 どこが間違っているのか全く分かりません。 どなたか詳しい方がいらっしゃればどうかアドバイスお願いします。

    • ベストアンサー
    • Mac
  • AppleScriptでiCalを動かしてみたが

    以前に下記のようなAppleScriptがネット上に有りましたが(1999年12月28日) ----------------------------------------------実行 set dSta to my date "2013年6月4日火曜日 0:00:00" set dEnd to my date "2013年6月4日火曜日 16:00:00" -- 検索するカレンダー名 set calName to "仕事" -- 結果を格納する変数 set copyText to "" tell application "Calendar" set theList to every event of calendar calName whose (start date ≥ dSta) and (end date ≤ dEnd) repeat with x in theList set aDate to (start date of x) set copyText to copyText & (aDate as text) & tab & summary of x & (ASCII character 10) end repeat end tell -- 結果をクリップボードにコピー set copyText2 to my Sortsc(copyText) set the clipboard to copyText2 on Sortsc(aData) do shell script "echo " & quoted form of aData & " | sort -d" end Sortsc ------------------------------------------------------------- 今回これを利用したい思い osx10.8 applescript エディタ2.5.1にて起動してみようとしましたが下記のような不思議な現象がでました。 set dSta to my date "2013年6月4日火曜日 0:00:00" set dEnd to my date "2013年6月4日火曜日 16:00:00" としていますが date "1999年12月28日火曜日 0:00:00" and end date ≤ date "1999年12月28日火曜日 16:00:00" となってしまった。 なぜそうなったのかが分かりません。 どなたかご存知のお方がおられましたらご教授いただきたいのですが。 -----------------------------------返された値 tell application "Calendar" get every event of calendar "仕事" whose start date ≥ date "1999年12月28日火曜日 0:00:00" and end date ≤ date "1999年12月28日火曜日 16:00:00" --> {} end tell tell current application do shell script "echo '' | sort -d" --> "" end tell tell application "AppleScript Editor" set the clipboard to "" end tell ------------------------------------------------------------- 因にosx10.6 AppleScript2.3にはきちんと返された値は内容が取得されています。

    • ベストアンサー
    • Mac
  • AppleScriptで

    kのディレクトリ内にあるインデックス番号がjのファイルの名前をiにだいにゅうしたくて set i to name of item index j of k ト書きましたがエラーになりました。なぜでしょう。助けてください。

    • ベストアンサー
    • Mac
  • chmodをapplescriptで実行したい。

    はじめまして AppleScript初心者です。 OSXServer10.4.8でファイル共有しています。 フォルダのアクセス権を定期的にchownコマンドで変更したいと思いますが、うまくいきません。 Applescriptでchmodコマンドを実行するものを用意しましたが、スクリプトエディタでスクリプトファイルを実行するとchmodでアクセス権が変更されるのですが、このスクリプトをcrontabに登録して特定の時間に実行するように設定すると機能しません。 AppleScript//////////////////// set cmdchown to "/usr/sbin/chown -R test /test1" do shell script cmdchown password "password" with administrator privileges set cmdchmod to "/bin/chmod -R 755 /test1" do shell script cmdchmod password "password" with administrator privileges ////////////////////////// 定期的にオーナーとアクセス権を変更するにはどうすれば良いですか? よろしくお願いします。

  • AppleScriptの記述方法で困っています。

    XcodeでAppleScriptを使用してプログラミングしています。 WebKit frameworkを用いて、webviewの機能をつくり、textfieldにURLを入力しリターンキーを押すと、webページがwebviewに表示される仕組みになっています。(takeStringURLFrom:の機能を使っています) そこで、リターンキーを押さずに自動的にwebページが表示されるようにAppleScriptでプログラムを組みたいのですが どのようにプログラムを記述すればいいのか分かりません。 例えばabcという変数にhttp://www.yahoo.co.jp/を入れて set contents of text field "textfield" of window "main" to abc というプログラムを組んでいます。 その後の記述が分からないのですが、どなたか詳しい方がいらっしゃれば アドバイスして頂けないでしょうか。 どうか宜しくお願いします。