Extract file extension from file path

前端 未结 5 1335
太阳男子
太阳男子 2020-12-03 09:51

How can I extract the extension of a file given a file path as a character? I know I can do this via regular expression regexpr(\"\\\\.([[:alnum:]]+)$\", x), b

相关标签:
5条回答
  • 2020-12-03 09:54

    This is the sort of thing that easily found with R basic tools. E.g.: ??path.

    Anyway, load the tools package and read ?file_ext .

    0 讨论(0)
  • 2020-12-03 09:59

    This function uses pipes:

    library(magrittr)
    
    file_ext <- function(f_name) {
      f_name %>%
        strsplit(".", fixed = TRUE) %>%
        unlist %>%
        extract(2)
     }
    
     file_ext("test.txt")
     # [1] "txt"
    
    0 讨论(0)
  • 2020-12-03 10:06

    simple function with no package to load :

    getExtension <- function(file){ 
        ex <- strsplit(basename(file), split="\\.")[[1]]
        return(ex[-1])
    } 
    
    0 讨论(0)
  • 2020-12-03 10:06

    The regexpr above fails if the extension contains non-alnum (see e.g. https://en.wikipedia.org/wiki/List_of_filename_extensions) As an altenative one may use the following function:

    getFileNameExtension <- function (fn) {
    # remove a path
    splitted    <- strsplit(x=fn, split='/')[[1]]   
    # or use .Platform$file.sep in stead of '/'
    fn          <- splitted [length(splitted)]
    ext         <- ''
    splitted    <- strsplit(x=fn, split='\\.')[[1]]
    l           <-length (splitted)
    if (l > 1 && sum(splitted[1:(l-1)] != ''))  ext <-splitted [l] 
    # the extention must be the suffix of a non-empty name    
    ext
    

    }

    0 讨论(0)
  • 2020-12-03 10:08

    Let me extend a little bit great answer from https://stackoverflow.com/users/680068/zx8754

    Here is the simple code snippet

      # 1. Load library 'tools'
      library("tools")
    
      # 2. Get extension for file 'test.txt'
      file_ext("test.txt")
    

    The result should be 'txt'.

    0 讨论(0)
提交回复
热议问题