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

查看:330
本文介绍了如何快速将file.info()的大小元素从字节转换为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(每个

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
    

  • 从那里,我被困住了.我意识到我可以做一些复杂的/手动的解析和计算来进行转换(请参阅

    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()的大小元素从字节转换为KB,MB,GB等?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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