AppleScript如何将文件路径写入文本文件

时间:2015-07-24 03:20:31

标签: applescript

我即将为AppleScript构建新功能。

我希望能够提示用户选择Excel文件,然后处理该Excel文件。

新功能是我想存储用户上次选择的文件的文件路径,以便下次执行脚本时,对话框将打开到同一文件夹。

我的对话框正常工作,我也有文件写入工作。

我的问题是我希望能够将文件路径写入文本文件,但我不知道如何。

请考虑以下代码:

set theFile to choose file with prompt "Please choose a file:" of type {"XLSX", "APPL"}
display dialog (theFile as string)

set outputFile to (("Macintosh HD:Users:lowken:Documents:") & "LaunchAgent_Alert.txt") 

try
    set fileReference to open for access file outputFile with write permission
    write theFile to fileReference
    close access fileReference
on error
    try
        close access file outputFile
    end try
end try

代码有效,但是我在输出文件中得到了垃圾:

>Macintosh HDÀ·q†H+÷œMiamieMasterMind.xlsxó∑èœÇäRXLSXXCELˇˇˇˇI À·©‡œÇ¬í,MiamieMasterMind.xlsxMacintosh HD*Users/lowken/Dropbox/MiamieMasterMind.xlsx/
ˇˇ

我的猜测是,我有文件编码问题,或者我需要从文件输出文件路径。

感谢您的帮助。

3 个答案:

答案 0 :(得分:2)

尝试使用属性,脚本将为您完成所有工作:

property theContainer : null
property theFile : null

set theFile to choose file with prompt "Please choose a file:" of type {"XLSX", "APPL"}
tell application "Finder" to set theContainer to theFile's container

从AppleScript语言指南:

  

在脚本所在的脚本之后,属性的值仍然存在   属性已定义已运行。因此,currentCount的值为0   这个脚本第一次运行,下次运行时就是1,等等   上。属性的当前值与脚本对象一起保存   在重新编译脚本之前不会重置为0,即修改后的脚本   然后再次运行,保存或检查语法。

答案 1 :(得分:2)

Craig解释的财产使用是最简单的解决方案。 如果重新编译脚本,将重置属性值。

但是,如果您确实需要将路径值存储在txt文件中以供其他脚本使用,则只需编写该文件,而不是别名,而是字符串:

write (theFile as string) to fileReference

当然,稍后阅读文本文件时,请记住它是一个字符串而不是别名!

答案 2 :(得分:1)

您可以保存AppleScript的类并将其读作(类型类)。

实施例

  1. write theFile to fileReference - theFile是AppleScript的别名

    像这样阅读 - > set theFile to read file "Macintosh HD:Users:lowken:Documents:LaunchAgent_Alert.txt" as alias

  2. 如果您保存列表:

    write myList to fileReference - myList是一个 appleScript的列表

    像这样阅读 - > set myList to read file "Macintosh HD:Users:lowken:Documents:LaunchAgent_Alert.txt" as list

  3. 如果您保存记录 - > {b:“15”,c:“éèà”}

    write myRecord to fileReference - myRecord是一个AppleScript版 记录

    像这样阅读 - > set myRecord to read file "Macintosh HD:Users:lowken:Documents:LaunchAgent_Alert.txt" as record

  4. 如果您保存真实 - > 200.123

    write floatNumber to fileReference - floatNumber是一个appleScript的 编号

    像这样阅读 - > set floatNumber to read file "Macintosh HD:Users:lowken:Documents:LaunchAgent_Alert.txt" as real

  5. 如果您保存一个整数 - > 20099

    write xNum to fileReference - xNum是一个appleScript的整数

    像这样阅读 - > set xNum to read file "Macintosh HD:Users:lowken:Documents:LaunchAgent_Alert.txt" as integer

  6. 如果您保存字符串 - > “éèà:376rrrr”

    write t to fileReference - t是一个appleScript的字符串

    像这样阅读 - > set t to read file "Macintosh HD:Users:lowken:Documents:LaunchAgent_Alert.txt" as string

  7. 重要提示:set eof to 0在将新内容写入现有文件之前

    set fileReference to open for access file outputFile with write permission
    set eof fileReference to 0
    write something to fileReference
    close access fileReference
    
相关问题