如何在R中为macOS文件写入并读取「显示简介」中的注释元数据?
如何在R中为macOS文件写入并读取「显示简介」中的注释元数据?
我之前也碰到过完全一样的需求——想在R里给macOS文件「显示简介」(Get Info)里的“注释”字段写入内容,之后还能在R里读取。最开始我也找过有没有类似Python的osxmetadata那样的R专用包,可惜没找到合适的,不过后来通过AppleScript结合R的system()命令搞定了,分享一下我的解决方案:
1. 最初的Shell脚本尝试(不推荐)
一开始我写了个外部Shell脚本update_comment.sh来处理:
filepth="$1" updated="$2" /usr/bin/osascript -e "set filepath to POSIX file \"$filepth\"" -e "set the_File to filepath as alias" -e "tell application \"Finder\" to set the comment of the_File to \"$updated\""
然后在R里调用这个脚本:
system("sh update_comment.sh test.rds 'Changing the comment to this'")
但这种方式依赖外部文件,每次用都得带着脚本,很不方便,所以我就琢磨能不能直接在R里写命令。
2. 直接在R中执行(推荐)
经过反复调整转义字符,终于找到正确的写法——把AppleScript的语句用单引号包裹,内部的文件路径和注释内容用双引号,这样就能直接在system()里执行,不需要外部脚本:
system("/usr/bin/osascript -e 'set filepath to POSIX file \"test.rds\"' -e 'set the_File to filepath as alias' -e 'tell application \"Finder\" to set the comment of the_File to \"Changing the comment to this\"'")
3. 封装成可复用的R函数
为了日常使用更方便,我把这个逻辑封装成了一个函数,还加上了屏蔽冗余输出的参数:
add_comment <- function(file, comment){ system(paste0("/usr/bin/osascript -e 'set filepath to POSIX file \"", file, "\"' -e 'set the_File to filepath as alias' -e 'tell application \"Finder\" to set the comment of the_File to \"", comment, "\"'"), ignore.stdout = TRUE, ignore.stderr = TRUE) }
调用的时候直接传文件路径和注释内容就行:
add_comment("test.rds", "这是我给文件加的自定义注释")
额外补充:读取文件的注释字段
如果之后想在R里读取这个注释内容,也可以用类似的方法封装一个读取函数:
get_comment <- function(file){ comment_content <- system(paste0("/usr/bin/osascript -e 'set filepath to POSIX file \"", file, "\"' -e 'set the_File to filepath as alias' -e 'tell application \"Finder\" to get the comment of the_File'"), intern = TRUE) return(comment_content) }
调用get_comment("test.rds")就能返回该文件的注释内容了。
备注:内容来源于stack exchange,提问作者henryelj
相关产品推荐
相关产品推荐

