【问题标题】:How to check file size before opening?打开前如何检查文件大小?
【发布时间】:2015-08-15 08:14:38
【问题描述】:

如何在将文件加载到 R 之前检查文件的大小?

例如:

http://math.ucdenver.edu/RTutorial/titanic.txt

我想根据文件大小使用最优命令打开文件。

【问题讨论】:

标签: r download unzip filesize


【解决方案1】:

使用file.info()

file.info("data/ullyses.txt")

                    size isdir mode               mtime               ctime               atime  uid  gid
data/ullyses.txt 1573151 FALSE  664 2015-06-01 15:25:55 2015-06-01 15:25:55 2015-06-01 15:25:55 1008 1008

然后提取名为size的列:

file.info("data/ullyses.txt")$size
[1] 1573151

【讨论】:

  • 如果它来自“http:”,有没有办法在加载前测量尺寸?
  • 您可能必须使用download.file(),然后在本地检查文件大小。
  • 从 R 3.2 开始有一个 file.size() 包装器。
【解决方案2】:
library(RCurl)
url = "http://math.ucdenver.edu/RTutorial/titanic.txt"
xx = getURL(url, nobody=1L, header=1L)
strsplit(xx, "\r\n")

【讨论】:

    【解决方案3】:

    也许自本次讨论以来已添加,但至少对于 R3.4+,答案是file.size

    【讨论】:

      【解决方案4】:

      如果您不想在知道文件大小之前下载文件,您可以尝试以下方法:

      注意:这只适用于 Mac 或 Linux。

      file_url = 'http://math.ucdenver.edu/RTutorial/titanic.txt'
      curl_cmd = paste('curl -X HEAD -i', file_url)
      system_cmd = paste(curl_cmd, '|grep Content-Length |cut -d : -f 2')
      

      上面将使用system() 打包一个要执行的字符串。 curl_cmd 字符串告诉 curl 只获取文件的标题。

      system_cmd 字符串包含一些额外的命令来解析标头并仅提取文件大小。

      现在,调用 system() 并使用 intern = TRUE 参数告诉 R 保持输出。

      b <- system(system_cmd, intern = TRUE)
      ##  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current 
      ##                              Dload  Upload   Total   Spent    Left  Speed
      ##   0     0    0     0    0     0      0      0 --:--:-- --:--:-- --:--:-- 0   
      ## curl: (18) transfer closed
      

      它将仅下载文件的标头并对其进行解析以获取文件大小。现在b 将是文件大小(以字节为单位)。


      然后你可以决定如何打开文件,或者打印一些友好的东西,比如:

      print(paste("There are", as.numeric(b)/1e6, "mb in the file:", file_url))
      ## [1] "There are 0.055692 mb in the file: http://math.ucdenver.edu/RTutorial/titanic.txt"
      

      【讨论】:

      • 如果有人可以共享一个适用于所有主机环境的解决方案,那就太棒了。我试着在RCurl 中摆弄了大约五分钟,但没走多远。
      • 太棒了!好多了。
      猜你喜欢
      • 2012-02-17
      • 1970-01-01
      • 1970-01-01
      • 2018-04-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-07
      • 1970-01-01
      相关资源
      最近更新 更多