Search code examples
csvpdfautomationapplescriptautomator

Copy PDF and name as values from CSV and create folders


I'd like to make my life a bit easier when organising student work. I'm struggling to come up with the correct workflow in Automator/Applescript.

CSV LIST:

  • Student A
  • Student B
  • Student C

PDF File: MarkScheme.pdf

Heres what I would like to happen:

  1. Create a folder for each student in the CSV File, named as 'StudentA'
  2. Copy the PDF file into each folder, named 'MarkScheme-StudentA'

The final folder (for each student) should look like this:

 - StudentA
 -- MarkScheme-StudentA.pdf
 - StudentB
 -- MarkScheme-StudentB.pdf
- StudentC
 -- MarkScheme-StudentC.pdf

What's the best way to achieve this? Many Thanks.


Solution

  • The Applescript bellow does what you want.

    I added some comments to make it clear :

    set FCsv to choose file with prompt "Select your CSV file with students"
    set Dest to choose folder with prompt "Select master folder"
    set FPDF to choose file with prompt "Select your PDF file"
    tell application "Finder" to set PdfName to name of FPDF
    set PdfName to text 1 thru ((offset of ".pdf" in PdfName) - 1) of PdfName -- get PDF name without .pdf extension
    
    set Fcontent to read FCsv -- read all cvs file
    set FLines to every paragraph of Fcontent
    repeat with aStudent in FLines -- loop through each line of the cvs file
    tell application "Finder"
        try -- try to create folder Student in master folder : assumption, it does not exist before !
            set SubFolder to make new folder in Dest with properties {name:aStudent}
        end try
        set SFolder to SubFolder as string
        -- use 'cp' shell command to copy with new name
        do shell script "cp " & (quoted form of (POSIX path of FPDF)) & " " & (quoted form of ((POSIX path of SFolder) & PdfName & "-" & aStudent & ".pdf"))
    end tell
    end repeat