AppleScript:使用path to command时写入文件的垃圾值

时间:2015-07-05 08:55:55

标签: applescript writetofile

我正在尝试编写一个简单的AppleScript,用于组织任何所选文件夹中的文件。我想让脚本以特定的时间间隔运行,并在事情发生变化时重新组织文件夹。为此,我试图将用户选择的文件夹的路径保存到文件。每次脚本运行时,它都会从该文件中读取文件夹路径。

这是代码中的代码段:

set home_path to get path to home folder

tell application "Finder"
    set home_folder to folder (home_path as string)
    if not (exists file "Clfd_config.cf1" in home_folder) then
        set (folder_path) to choose folder with prompt "Choose the folder to organize"
        set this_folder to folder (folder_path as string)
        set path_file to open for access file (home_path & "Clfd_config.cf1" as text) with write permission
        write folder_path to path_file
        close access path_file
    else
        set path_file to open for access file (home_path & "Clfd_config.cf1" as   string)
        set folder_path to read path_file as string
        set this_folder to folder (folder_path as string)
        close access path_file

    end if
end tell

但是,当我打开文件时,它会出现乱码信息,如下所示:

������Harshad��������������������œ‘xH+���   7    Desktop�����������������������������������������    ����������������   7Éœ‘zç��������ˇˇˇˇ��I ����������    ������œ‘*∆������œ‘-5������D�e�s�k�t�o�p���    �H�a�r�s�h�a�d��Users/harshad/Desktop���/����ˇˇ������

当我尝试在脚本中读取此文件时,脚本显然会失败。

我已经尝试告诉脚本将文件写为字符串,作为文本,但我不断收到错误,即folder_path变量无法转换为文本或字符串。

我该怎么做才能正确保存路径并且脚本可以从保存的文件中读取它?

2 个答案:

答案 0 :(得分:0)

主要问题是您正在为磁盘而不是字符串路径编写别名文件说明符。

我在写入磁盘时添加了基本的错误处理并删除了一些冗余代码

property configFileName : "Clfd_config.cf1"

tell application "Finder"
    set configFile to (home as text) & configFileName
    if not (exists file configFile) then
        set folder_path to choose folder with prompt "Choose the folder to organize"
        try
            set fileReference to open for access file configFile with write permission
            write (folder_path as text) to fileReference
            close access fileReference
        on error
            try
                close access file configFile
            end try
        end try
    else
        set folder_path to read file configFile
        set this_folder to folder folder_path
    end if
end tell

答案 1 :(得分:0)

您似乎只想保存文件夹路径的值,并能够在下次运行时再次找到它。 如果只是那个,为什么你使用子程序将此路径写入特定位置的文本文件?你是否更容易使用“属性”对象的特征?

“Property”变量可以更改,并在脚本本身保留新值,直到下一次编译。

试试这个脚本:第一次运行,它会询问你的文件夹。选择它。任何下一次运行,它只会显示首次运行时选择的文件夹!

property My_Folder : ""
if My_Folder is "" then -- first run, ask user to select folder
    Set My_Folder to (choose folder with prompt "choose the folder to organise") as string
end if
display dialog "folder selected = " & My_Folder

它与文本文件中的读/写相同...