利用R语言批量修改文件名file.rename函数

利用R语言批量修改文件名file.rename函数

R语言中文件操作的函数有:

file.create(…, showWarnings = TRUE)
file.exists(…)
file.remove(…)
file.rename(from, to)
file.append(file1, file2)
file.copy(from, to, overwrite = recursive, recursive = FALSE,
copy.mode = TRUE, copy.date = FALSE)
file.symlink(from, to)
file.link(from, to)
Sys.junction(from, to)

file.rename()函数使用方法:file.rename(源文件名,修改的文件名),此处文件名必须为character格式可以用as.character()函数将data.frame等格式转换。

其他用法:

umxRenameFile <- function(baseFolder = "Finder", findStr = NA, replaceStr = NA, listPattern = NA, test = T, overwrite = F) {
    # uppercase = u$1
    if(baseFolder == "Finder"){
        baseFolder = system(intern = T, "osascript -e 'tell application \"Finder\" to get the POSIX path of (target of front window as alias)'")
        message("Using front-most Finder window:", baseFolder)
    } else if(baseFolder == "") {
        baseFolder = paste(dirname(file.choose(new = FALSE)), "/", sep = "") ## choose a directory
        message("Using selected folder:", baseFolder)
    }
    if(is.na(listPattern)){
        listPattern = findStr
    }
    a = list.files(baseFolder, pattern = listPattern)
    message("found ", length(a), " possible files")
    changed = 0
    for (fn in a) {
        findB = grepl(pattern = findStr, fn) # returns 1 if found
        if(findB){
            fnew = gsub(findStr, replace = replaceStr, fn) # replace all instances
            if(test){
                message("would change ", fn, " to ", fnew)  
            } else {
                if((!overwrite) & file.exists(paste(baseFolder, fnew, sep = ""))){
                    message("renaming ", fn, "to", fnew, "failed as already exists. To overwrite set T")
                } else {
                    file.rename(paste(baseFolder, fn, sep = ""), paste(baseFolder, fnew, sep = ""))
                    changed = changed + 1;
                }
            }
        }else{
            if(test){
                # message(paste("bad file",fn))
            }
        }
    }
    message("changed ", changed)
}

如若转载,请注明出处:https://www.ouq.net/241.html

(6)
打赏 微信打赏,为服务器增加50M流量 微信打赏,为服务器增加50M流量 支付宝打赏,为服务器增加50M流量 支付宝打赏,为服务器增加50M流量
上一篇 03/24/2020 00:54
下一篇 03/26/2020 01:28

相关推荐

  • R:使用GOplot对GO分析结果作图

    安装 # Installation of the latest released version install.packages(‘GOplot’) # Installation of the latest development ver…

    04/28/2022
    278
  • R:字符大小写转换

    R:字符大小写转换 >x = “CAGGGT” #定义字符串变量x >tolower(x) [1] “caggt” #将x中的字符全部转换为小写字母 >y = tolower…

    R 08/10/2021
    117
  • R:计算数据框中每一行的标准偏差

    RowSD = function(x) {sqrt(rowSums((x – rowMeans(x))^2)/(dim(x)[2] – 1))}

    R 04/21/2022
    185
  • dplyr包筛选数据

    dplyr与安装 dplyr是一个强大的R软件包,用于处理,清理和汇总非结构化数据。简而言之,它使得R中的数据探索和数据操作变得简单快捷。 最简单的方法是安装 tidyverse包: install.packages(“tidyverse”…

    03/17/2020
    799
  • had non-zero exit status

    解决方案1:install.packages(‘*package_name’, dependencies = TRUE)

    Python 11/07/2020
    126