为什么我的applescript用于检查文件是否存在失败?


1

我有一个applescript应用程序,可以输入用户名并根据该用户名开始下载。在应用程序中,我使用下面的代码检查文件是否已经存在,然后将其重命名。

tell application "Finder"
if exists "~/Downloads/Conversion/" & cbUsername & ".flv" as POSIX file then
    set x to 1
    repeat
        set newCbFilename to cbUsername & "_" & x as string
        if exists "~/Downloads/Conversion/" & newCbFilename & ".flv" as POSIX file then
            set x to x + 1
        else
            exit repeat
        end if
    end repeat
    copy newCbFilename to finalCbFilename
    display dialog "Filename already exists " & "File will be named: " & finalCbFilename & ".flv" buttons "OK" default button "OK" with title "Error" with icon caution
else
    copy cbUsername to finalCbFilename
end if
end tell

昨天突然间,它停止正常工作。我添加了以下代码,以确保要保存到的文件夹存在。

tell application "System Events"
if not (exists folder "~/Downloads/Conversion") then
    do shell script "mkdir ~/Downloads/Conversion"
end if

即使现在我注释掉该代码,它仍然也不起作用。我做错了什么?结束告诉

Answers:


4

看起来Finder需要到主文件夹的绝对路径,而不是相对路径。它不是从开始,而是从~/开始/Users/username/

您可以让AppleScript动态构建绝对路径,而不是将用户名硬编码到脚本中:

set homePath to POSIX path of (path to home folder)

然后您可以替换"~/homePath & "

例如:

if exists "~/Downloads/Conversion/" & cbUsername & ".flv" as POSIX file then

会成为

if exists homePath & "Downloads/Conversion/" & cbUsername & ".flv" as POSIX file then

另外,如果仅使用~path ~/Downloads/Conversion/,则可以将整个路径更改为变量:

set cbPath to POSIX path of (path to home folder) & "Downloads/Conversion/"

那么最终的脚本将是:

set cbPath to POSIX path of (path to home folder) & "Downloads/Conversion/"

tell application "Finder"
    if exists cbPath & cbUsername & ".flv" as POSIX file then
        set x to 1
        repeat
            set newCbFilename to cbUsername & "_" & x as string
            if exists cbPath & newCbFilename & ".flv" as POSIX file then
                set x to x + 1
            else
                exit repeat
            end if
        end repeat
        copy newCbFilename to finalCbFilename
        display dialog "Filename already exists " & "File will be named: " & finalCbFilename & ".flv" buttons "OK" default button "OK" with title "Error" with icon caution
    else
        copy cbUsername to finalCbFilename
    end if
end tell

1
好吧,我会尝试的。我很好奇为什么它决定现在停止工作了。在我添加了我提到的代码之前,它一直运行良好。O_o
Eli Greenberg

@EliGreenberg如果答案确实回答了您的问题,请将其标记为已接受的答案。
2016年
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.