在Linux中,我们可以使用file
命令基于文件内容(而不是扩展名)获取文件类型。在R中是否有类似的函数?
虽然这是一个老问题,但对于通过谷歌搜索到这里的人可能仍有参考价值:您可以使用 dqmagic(一个基于libmagic的R包装器)来根据文件内容确定文件类型。由于file
使用相同的库,因此结果是相同的,例如:
library(dqmagic)
file_type("DESCRIPTION")
#> [1] "ASCII text"
file_type("src/file.cpp")
#> [1] "C source, ASCII text"
对比。
$ file DESCRIPTION src/file.cpp
DESCRIPTION: ASCII text
src/file.cpp: C source, ASCII text
免责声明:我是该软件包的作者。
dqmagic并未在CRAN上发布。以下是一个使用Linux的“file”命令(实际上是基于BSD的'file' v5.35,日期为2018年10月,根据man页面,在Ubuntu 19.04中打包)的R解决方案。
file_full_path <- "/home/user/Documents/an_RTF_document.doc"
file_mime_type <- system2(command = "file",
args = paste0(" -b --mime-type ", file_full_path), stdout = TRUE) # "text/rtf"
# Gives the list of potentially allowed extension for this mime type:
file_possible_ext <- system2(command = "file",
args = paste0(" -b --extension ", file_full_path),
stdout = TRUE) # "???". "doc/dot" for MsWord files.
有时需要检查实际的扩展名是否为给定的MIME类型合法的扩展名(例如,readtext::readtext() 可以读取RTF文件,但如果以*.doc格式保存,则会失败)。
file.basename <- basename(file_full_path)
file.base_without_ext <-sub(pattern = "(.*)\\..*$",
replacement = "\\1", file.basename)
file.nchar_ext <- nchar(file.basename) -
nchar(file.base_without_ext)-1 # 3 or 4 (doc, docx, odt...)
file_ext <- substring(file.basename, nchar(file.basename) -
file.nchar_ext +1) # doc, rtf...
if (file_mime_type == "text/rtf"){
file_possible_ext <- "rtf"
} # in some (all?) cases, for an rtf mime-type,
#'file' outputs "???" as allowed extension
# Returns TRUE if the actual extension is known to
# be a valid extension for the given mime type:
length(grep(file_ext, file_possible_ext, ignore.case = TRUE)) > 0