Applescript根据.CSV值创建文件夹并从weblink下载文件到那些创建的文件夹

时间:2017-12-12 22:32:36

标签: applescript

在我的示例.CSV文件中,我有一个包含以下值的列A:2,2,5,5,5。在B列中是指向需要下载的相应文件的超链接:http://example.com/2A.pdfhttp://example.com/2B.pdfhttp://example.com/5A.pdfhttp://example.com/5B.pdfhttp://example.com/5BC.pdf。难以创建创建DL文件夹的AppleScript(基于非唯一列A值)并将任何相应行的DL应用于相应的文件夹。任何帮助将不胜感激! TIA。

1 个答案:

答案 0 :(得分:0)

根据您的描述,我假设CSV文件看起来像这样:

2, http://example.com/2A.pdf
2, http://example.com/2B.pdf
5, http://example.com/5A.pdf
5, http://example.com/5B.pdf
5, http://example.com/5BC.pdf

并且文件 2A.pdf 应该在名为 2 的目录中结束。

假设我已经正确解释了这一点,这里是实现此目的的AppleScript(将 / Path / To / Save / Folder / 替换为这些新文件和文件夹所在文件夹的完整路径下载, /Path/To/File.csv 到CSV文件的完整路径):

    -- Note: The ending / is essential in BaseDir
    set BaseDir to POSIX file "/Path/To/Save/Folder/"
    set rows to every paragraph of (read "/Path/To/File.csv")

    set AppleScript's text item delimiters to {"/"}

    set [TopDir, BaseFolder] to [text items 1 thru -3, text item -2] of ¬
        POSIX path of BaseDir


    -- Create initial base folder if it doesn't exist
    tell application "Finder" to if not (exists BaseDir) then ¬
        make new folder in (TopDir as text as POSIX file) ¬
        with properties {name:BaseFolder}

    -- This will prevent EOF-related errors
    -- Thanks to @user3439894 for highlighting the need for this
    set rows to reverse of rows
    if the number of words of the first item in rows is 0 ¬
        then set rows to the rest of rows

    repeat with row in rows

        set [N, |url|] to [first word, text items -2 thru -1] of row

        -- Create folder into which file will be downloaded
        tell application "Finder" to if not (exists [BaseDir, N] as text) then ¬
            make new folder in BaseDir with properties {name:N}

        -- This is the shell command that downloads the file
        -- e.g. "cd '/Users/CK/Desktop/example.com/5'; curl example.com/5BC.pdf \
        --       remote-name --silent --show-error"
        set command to ("cd " & ¬
            quoted form of POSIX path of ([BaseDir, N] as text) & ¬
            "; curl " & |url| as text) & ¬
            " --remote-name --silent --show-error"

        -- Run the shell command
        do shell script command

    end repeat

    -- Open folder in Finder upon completion of downloads
    tell application "Finder"
        activate
        open BaseDir
    end tell

我应该强调,这是一个强大的脚本,旨在用于各种情况的一般用途,而是一个专门针对所描述的案例量身定制的示例脚本。如果您的CSV文件与我的假定格式略有不同,则可能会发生错误。