3

file.size() function returns the file size in Bytes. How can we convert the returned bytes into KB, MB, GB or TB accordingly?

For e.g.

255Bytes = 255B
19697Bytes = 19.24KB
13230426Bytes = 12.62MB
  • 1
    Possible dupe? https://stackoverflow.com/q/63459178/3358272 (it's an imperfect dupe, but it asks just a little more than this question does ... it's a "super-set" of this question) – r2evans Aug 23 '20 at 06:06
  • From my answer there, use `KMG(c(255, 19697, 13230426), suffix="B", standard="legacy")` and get `[1] "255B" "19.7KB" "13.2MB"`. – r2evans Aug 23 '20 at 06:09
  • 2
    I can't answer because it's been duped, but you can use the `utils:::format.object_size` function to do it in a roundabout way - `utils:::format.object_size(file.size("filename.r"), "Mb")` for example that can convert to “B”, “kB”, “MB”, “GB”, “TB”, “PB”, “EB”, “ZB”, “YB”, “KiB”, “MiB”, “GiB”, “TiB”, “PiB”, “EiB”, “ZiB”, “YiB”, “b”, “Kb”, “Mb”, “Gb”, “Tb”, “Pb”, and “KB”. – thelatemail Aug 23 '20 at 06:16

2 Answers2

1

We could try a brute force approach using case_when from the dplyr package:

library(dplyr)
input <- 123456    # numerical input as number of bytes
output <- case_when(
    input < 1000 ~    paste0(input, "B"),
    input < 1000000 ~ paste0(input / 1000, "KB"),
    input < 1000000000 ~ paste0(input / 1000000, "MB"),
    input < 1000000000000 ~ paste0(input / 1000000000, "GB"),
    input < 1000000000000000 ~ paste0(input / 1000000000, "TB"),
    TRUE ~ paste0(input, "B")  # for anything larger than 999TB, just report bytes
)
output

[1] "123.456KB"
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
1

I have found various solutions in other programming languages. But this post has a solution suggested by @Rohit Jain which is working fine. With small tweaks implemented it in an R function:


file_size_formated <- function(size){
  
  k = size/1024.0 ^ 1
  m = size/1024.0 ^ 2
  g = size/1024.0 ^ 3
  t = size/1024.0 ^ 4
  
    if (t > 1) {
      outSize = paste0(round(t,2),"TB")
    } else if (g > 1) {
      outSize = paste0(round(g,2),"GB")
    } else if (m > 1) {
      outSize = paste0(round(m,2),"MB")
    } else if (k > 1) {
      outSize = paste0(round(k,2),"KB")
    } else{
      outSize = paste0(round(size,2),"B")
    }
    
  return(outSize)
}

Let's say you want to get file sizes for all the files in "www" folder on your device:

# Normal output
 file.size(list.files("www",full.names = TRUE))

  [1]      255      307      856     1205     1038     5940      250     3940      328     1593    53938 59061210  3750711    16251    42756
 [16]     6709    19697 13230426

# Function Output

sapply(file.size(list.files("www",full.names = TRUE)),file_size_formated)

 [1] "255B"    "307B"    "856B"    "1.18KB"  "1.01KB"  "5.8KB"   "250B"    "3.85KB"  "328B"    "1.56KB"  "52.67KB" "56.33MB" "3.58MB"  "15.87KB"
[15] "41.75KB" "6.55KB"  "19.24KB" "12.62MB"