根据内容确定R中的文件类型

时间:2015-11-19 07:24:24

标签: r file

在linux中,我们可以使用file命令根据文件内容获取文件类型(不是扩展名)。 R中是否有类似的功能?

2 个答案:

答案 0 :(得分:3)

旧问题,但可能与通过谷歌到达此处的人有关:您可以使用dqmagic(围绕libmagic for R的包装)来确定基于文件内容的文件类型。由于file使用相同的库,因此结果相同,例如:

library(dqmagic)
file_type("DESCRIPTION")
#> [1] "ASCII text"
file_type("src/file.cpp")
#> [1] "C source, ASCII text"

VS

$ file DESCRIPTION src/file.cpp 
DESCRIPTION:  ASCII text
src/file.cpp: C source, ASCII text

免责声明:我是该套餐的作者。

答案 1 :(得分:0)

dqmagic不在CRAN上。在使用Linux的“文件”命令的R解决方案下方(根据手册页,实际上是BSD的“文件” v5.35日期为2018年10月,打包在Ubuntu 19.04中)

/html/body/div[contains(@class, 'product-detail-section') AND not contains(@class, 'tested-app-section')]/div[not(@class='product-container-head')]

可能有必要检查已知扩展名对于给定的mime类型是否有效(例如,readtext :: readtext()读取RTF文件,但如果另存为* .doc,则失败)

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.