使用Applescript将列表写入CSV

时间:2012-04-10 23:18:33

标签: csv applescript

我有一个从CSV读取数据的AppleScript(成功!)。在我的脚本完成编辑数据后,我希望它将修改后的文本写回该文件。   当我的文本被写回CSV文件时,它已经丢失了所有回车符,因此它显示为一行。我做错了什么?

set theFile to choose file with prompt "Select a text file:"
set theFileContents to read theFile
...


set theList to paragraphs of theFileContents



repeat with i from 2 to count theList

set AppleScript's text item delimiters to ","
set theLine to theList's item i
theLine
set clinic_id to first text item of theLine
....
set AppleScript's text item delimiters to ""

...

    open for access theFile with write permission

    set theData to theList as text
    write the [theData] to theFile as text
    close access theFile


    display dialog the [theLine]
end if
end repeat

有什么建议吗?此代码的输出是:

1,2,3,A,B,C,X,Y,Z

当我想要的是

1,2,3
A,B,C
X,Y,Z

1 个答案:

答案 0 :(得分:3)

我认为你的theList有行(每行都有一个带逗号的字符串)作为项目,所以它看起来像{"1,2,3", "A,B,C", "X,Y,Z"},对吧?因此,将列表转换为text之前将其写入文件,将text item delimiters设置为换行符:

set AppleScript's text item delimiters to "\n"
set theData to {"1,2,3", "A,B,C", "X,Y,Z"} as text

theData现在有值

"1,2,3
A,B,C
X,Y,Z"

这正是您在输出文件中找到的内容。