使用
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
也许是在这次讨论之后添加的,但至少对于 R3.4+,答案是
file.size
。
library(RCurl)
url = "http://math.ucdenver.edu/RTutorial/titanic.txt"
xx = getURL(url, nobody=1L, header=1L)
strsplit(xx, "\r\n")
除了上面提到的
file.size
之外,您还可以使用 file_size
包中的 fs
,它将以更易于理解的输出方式打印大小,显示 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
如果您不想在知道文件大小之前下载文件,您可以尝试以下操作:
注意:这仅适用于 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"
# Suppose you have a list of files named filelist. For example...
filelist = c("./myfile1.txt", "./myfile2.txt", "./myfile3.txt")
# The command above assumes that the files are in your current working directory "./"
# If your files are in a different location, you need to replace "./"
# with the path to the directory that holds the files
# or, if you have only one data file, filelist = "./myfile1.txt"
# To check which files meet a particular size criterion, you can use the command below.
# For example, the command below checks whether the file size is greater than 0.
# The final filelist includes only the file names that meet the criterion.
filelist = filelist[file.size(filelist)>0]
# If no files meet the criterion, then the final filelist will be "character(0)"