如何快速将 file.info() 的 size 元素从字节转换为 KB、MB、GB 等? [英] How do I quickly convert the size element of file.info() from bytes to KB, MB, GB, etc.?

查看:45
本文介绍了如何快速将 file.info() 的 size 元素从字节转换为 KB、MB、GB 等?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望在 stackoverflow 上已经有这个问题的答案,但我只是没能找到它.

I expect there is already an answer for this on stackoverflow, and I simply failed to find it.

期望的结果:快速将 file.info() 调用中的文件大小元素从字节转换为 KB、MB 等.如果输出我很好是 i) 具有所需大小类型的字符串,例如 "96 bytes" 或 ii) 简单的数字转换,例如从 60963 字节到 60.963 KB(每 Google).

Desired outcome: Quickly convert the file size element in a file.info() call from bytes to KB, MB, etc. I'm fine if the output is either i) a character string with the desired size type, e.g., "96 bytes" or ii) simply a numeric conversion, e.g., from 60963 bytes to 60.963 KB (per Google).

复制步骤:

  1. 创建一个文件夹来存放文件:

  1. Create a folder to store the file:

dir.create("census-app/data")

  • 下载文件(~60KB):

  • Download the file (~60KB):

    download.file("http://shiny.rstudio.com/tutorial/lesson5/census-app/data/counties.rds",
    "census-app/data/counties.rds")
    

  • 使用 file.info()$size 以字节为单位返回文件大小:

  • Use file.info()$size to return the file size in bytes:

    file.info("census-app//data//counties.rds")$size
    [1] 60963
    

  • 从那里,我被困住了.我意识到我可以进行一些复杂/手动解析和计算来进行转换(请参阅 将千字节、兆字节等转换为 R 中的字节).

    From there, I'm stuck. I realize I can do some complicated/manual parsing and calculation to make the conversion (see Converting kilobytes, megabytes etc. to bytes in R).

    但是,我希望我可以简单地使用基本函数或类似的东西:

    However, I'm hoping I can simply use a base function or something similar:

        format(file.info("census-app//data//counties.rds")$size, units = "KB")
        [1] "60963"
        # Attempt to return file size in KB simply returns the size in bytes
        # NOTE: format(x, units = "KB") works fine when I
        # pass it object.size() for an object loaded in R
    

    推荐答案

    object.size() 函数对其结果进行这种类型的格式化,但它的目的是告诉你您传递给它的 R 对象.它没有设置为任意值.

    The object.size() function does this type of formatting for it's results, but its meant to tell you the size of the R object you pass to it. It is not set up to take an arbitrary by value.

    但是,我们可以窃取"其中的一些格式逻辑.你可以调用它

    However, we can "steal" some of it's formatting logic. You can call it with

    utils:::format.object_size(60963, "auto")
    # [1] "59.5 Kb"
    

    这样我们就可以调用未导出的格式化函数.您可以在 ?format.object_size 帮助页面上调出其他格式选项.请注意,它使用 1 Kb = 1024 字节(而不是您的示例中的 1000)的规则.

    In that way we can call the un-exported formatting function. You can bring up the additional formatting options on the ?format.object_size help page. Note that it uses the rule that 1 Kb = 1024 bytes (not 1000 as in your example).

    这篇关于如何快速将 file.info() 的 size 元素从字节转换为 KB、MB、GB 等?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆