如何在打开文件之前检查文件大小?

40

4
?file.info可能是你想要的。 - cory
https://dev59.com/OHrZa4cB1Zd3GeqP8uoh 可能是你想要的。 - Anthony Damico
1
被接受的答案并不是最新的答案。 - gota
5个回答

58

使用 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:"加载的,有没有一种方法在加载之前测量大小? - Rhodo
1
你可能需要使用 download.file() 函数下载文件,然后在本地检查文件大小。 - Andrie
8
自 R 3.2 起,有一个 file.size() 包装器函数。 - Scarabee

10

也许在这次讨论之后做了更新,但至少在 R3.4+ 中,答案是 file.size


8
library(RCurl)
url = "http://math.ucdenver.edu/RTutorial/titanic.txt"
xx = getURL(url, nobody=1L, header=1L)
strsplit(xx, "\r\n")

1
如果您不想在下载文件之前了解其大小,可以尝试以下操作:
注:此方法仅适用于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 中摆弄了大约五分钟,但没什么进展。 - neerajt
1
https://dev59.com/OHrZa4cB1Zd3GeqP8uoh - Anthony Damico
太棒了!好多了。 - neerajt

1
除了上面提到的file.size之外,您还可以使用fs包中的file_size,它将以更易读的方式显示文件大小,显示MB或GB而不是字节。
例如,比较这两个函数返回的输出:
library(fs)

file.size(system.file("data/Rdata.rdb", package = "datasets"))
#> [1] 114974
fs::file_size(system.file("data/Rdata.rdb", package = "datasets"))
#> 112K

file.size(system.file("data/Rdata.rdb", package = "spData"))
#> [1] 2676333
fs::file_size(system.file("data/Rdata.rdb", package = "spData"))
#> 2.55M

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接