リストのCSV書き出し
リスト型変数をCSVファイルに書き出すサブルーチンです。ただし、このルーチンではデータ中に含まれたダブルクォートをエスケープする「サニタイズ」の処理を含んでいません。
スクリプト名:リストのCSV書き出し |
set aNewFile to choose file name –あくまでサンプルなので。普通はあらかじめパスのテキストを組み立てて渡すべし
set dataList to {{”0010“, “ひよこタオルギフト“, “200“, “手に取ったとき、使うとき、ちょっと楽しくてかわいいひよこのタオル。“, “●サイズ/H200㎜×W200㎜●素材/ひよこ羽毛100%●重量/170g●内容/5枚入り“}, {”0020“, “ひよこホイッスル“, “250“, “今までにないデザインの、ひよこ型のホイッスル。ぴよ〜音を音階で吹き分けます。“, “●サイズ/H60㎜×W40㎜×D10㎜●素材/プラスチック ●色/ひよこ色●重量/10g●付属品/首かけロープ付き ●型番/PIYO1“}} saveAsCSV(dataList, aNewFile) of me – CSV書き出し–ただし、データ内にダブルクォートが入っていた場合に備えてのサニタイズ処理は行っていない on saveAsCSV(aList, aPath) set crlfChar to (ASCII character 13) & (ASCII character 10) set LF to (ASCII character 10) set wholeText to “” repeat with i in aList set aLineText to “” set curDelim to AppleScript’s text item delimiters set AppleScript’s text item delimiters to “\”,\”“ set aLineList to i as text set AppleScript’s text item delimiters to curDelim set aLineText to repChar(aLineList, return, “”) of me –データの途中に改行が入っていた場合には削除する set aLineText to repChar(aLineText, LF, “”) of me –データの途中に改行が入っていた場合には削除する set wholeText to wholeText & “\”” & aLineText & “\”” & crlfChar –行ターミネータはCR+LF end repeat if (aPath as string) does not end with “.csv” then set bPath to aPath & “.csv” as Unicode text else set bPath to aPath as Unicode text end if write_to_file(wholeText, bPath, false) of me end saveAsCSV – ファイルの追記ルーチン「write_to_file」–追記データ、追記対象ファイル、boolean(trueで追記) on write_to_file(this_data, target_file, append_data) try set the target_file to the target_file as text 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 error_message try close access file target_file end try return error_message end try end write_to_file – 文字置換on repChar(origText, targChar, repChar) set origText to origText as string set targChar to targChar as string set repChar to repChar as string set curDelim to AppleScript’s text item delimiters set AppleScript’s text item delimiters to targChar set tmpList to text items of origText set AppleScript’s text item delimiters to repChar set retText to tmpList as string set AppleScript’s text item delimiters to curDelim return retText end repChar |