Как скопировать файл в папки и отредактировать переменную в файле на основе имени папки - PullRequest
0 голосов
/ 28 мая 2019

У меня есть файл .xml, который необходимо скопировать в каждую подпапку папки. В этом файле есть переменная, которую необходимо изменить, чтобы она отражала имя папки (без пути).

Код, который у меня есть, генерирует новые папки в выбранной главной папке. Он делает это, получая имена файлов (например, .jpgs) в этой папке, создавая новые папки с тем же именем и помещая каждый .jpg в соответствующую папку. Теперь мне нужно отредактировать переменную в xml, которую я настроил как «vID», а затем скопировать ее в каждый файл.

tell application "Finder"


    set selected to selection
    set current_folder to item 1 of selected
    set mlist to every file of current_folder
    set theFile to choose file (* XML file with variable *)
    set MyFolder to current_folder

    repeat with this_file in mlist
        set cur_ext to name extension of this_file
        set new_name to text 1 thru -((length of cur_ext) + 2) of (name of this_file as text)

        set stringToFind to "vID"
        set stringToReplace to new_name
        set theContent to read theFile as «class utf8»
        set {oldTID, AppleScript's text item delimiters} to {AppleScript's text item delimiters, stringToFind}
        set ti to every text item of theContent
        set AppleScript's text item delimiters to stringToReplace
        set newContent to ti as string
        set AppleScript's text item delimiters to oldTID
        try
            set fd to open for access theFile with write permission
            set eof of fd to 0
            write newContent to fd as «class utf8»
            close access fd
        on error
            close access theFile
        end try

        set new_folder to make new folder with properties {name:new_name} at current_folder




        move this_file to new_folder

        duplicate MyFile to new_folder

    end repeat



end tell

В настоящее время код правильно генерирует папки, перемещает файлы .jpgs в их папки, редактирует XML и дублирует его в каждой папке. Проблема в том, что переменная не отражает каждую папку. Это просто изменено на имя последней папки. Пожалуйста, дайте мне знать, если вам нужны дополнительные разъяснения.

1 Ответ

0 голосов
/ 29 мая 2019

Ваш XML-файл не обновляется, поскольку вы перезаписали шаблон, который заменил строку-заполнитель. Вы можете сделать копию шаблона и затем отредактировать копию или просто написать новое содержимое XML напрямую:

global base_template -- this will be the master template to copy
set base_template to (choose file with prompt "Choose the template file:" of type "com.apple.property-list") -- XML file with placeholder text to replace

tell application "Finder"
  set current_folder to item 1 of (get selection)
  repeat with this_file in (get files of current_folder)
    set {file_name, file_extension} to my getNamePieces(this_file)
    set new_folder to make new folder with properties {name:file_name} at current_folder
    move this_file to new_folder
    set new_template to (new_folder as text) & (name of base_template)
    my copyTemplate(file_name, new_template)
  end repeat
end tell

to copyTemplate(name_text, new_template) -- write edited copy of template
  set placeholder_text to "vID"
  set base_content to read base_template as «class utf8»
  set {temp_TID, AppleScript's text item delimiters} to {AppleScript's text item delimiters, placeholder_text}
  set {item_list, AppleScript's text item delimiters} to {text items of base_content, name_text}
  set {new_content, AppleScript's text item delimiters} to {item_list as text, temp_TID}
  try
    set fd to (open for access file new_template with write permission)
    write new_content to fd as «class utf8»
    close access fd
  on error errmess -- oops, make sure file gets closed
    log errmess
    close access fd
  end try
end copyTemplate

to getNamePieces(file_item) -- get base file name and extension
  tell application "System Events" to tell disk item (file_item as text) to set {_name, _extension} to {name, name extension}
  if _extension is not "" then
    set _name to text 1 thru -((count _extension) + 2) of _name
    set _extension to "." & _extension
  end if
  return {_name, _extension}
end getNamePieces
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...