【问题标题】:os.path.getsize reports a filesize with an L at the end, why?os.path.getsize 报告最后带有 L 的文件大小,为什么?
【发布时间】:2012-09-17 09:14:45
【问题描述】:
import os, sys

def crawlLocalDirectories(directoryToCrawl):
    crawledDirectory = [os.path.join(path, subname) for path, dirnames, filenames in os.walk(directoryToCrawl) for subname in dirnames + filenames]
    return crawledDirectory

print crawlLocalDirectories('.')

dictionarySize = {}
def getSizeOfFiles(filesToMeasure):
    for everyFile in filesToMeasure:
        size = os.path.getsize(everyFile)
        dictionarySize[everyFile] = size
    return dictionarySize

print getSizeOfFiles(crawlLocalDirectories('.'))

每次运行时,我都会得到{'example.py':392L} 的输出,为什么?什么是L?我不想在最后把 L 去掉。

如果我在不将其添加到字典的情况下运行它,它会返回文件大小为392

【问题讨论】:

  • 返回的文件大小可能是 long。
  • @xbonez -- 将其作为答案发布 -- 或许可以快速解释一下 long 实际上是什么
  • @Matthew -- 很好奇,这是什么操作系统?

标签: python dictionary filesize directory


【解决方案1】:

这仅在交互模式或通过repr() 获取字符串表示时才会显示。正如 zigg 所写,您可以简单地忽略它。考虑这是一个实现细节。当区分普通 int 和 long int 很重要时,它可能很有用。例如,在 Python 3 中,没有 L。 int 不管多大都是 int:

d:\>py
Python 3.2.1 (default, Jul 10 2011, 20:02:51) [MSC v.1500 64 bit (AMD64)] on win
32
Type "help", "copyright", "credits" or "license" for more information.
>>> a = 100000000000000000000000000000000000000000000
>>> a
100000000000000000000000000000000000000000000
>>> ^Z

d:\>python
Python 2.7.3 (default, Apr 10 2012, 23:24:47) [MSC v.1500 64 bit (AMD64)] on win
32
Type "help", "copyright", "credits" or "license" for more information.
>>> a = 100000000000000000000000000000000000000000000
>>> a
100000000000000000000000000000000000000000000L
>>>

注意 Python 2.7 的 L,但 Python 3.2 没有类似的东西。

【讨论】:

  • 啊,我明白了。这很有意义。作为初学者,我应该学习 Py3 还是继续 2.7?
  • 没关系。重要的事情都是一样的。但是,如果可能,我建议两者都尝试。我的猜测是 Python 3 很快就会获胜。看看getpython3.com/diveintopython3/strings.html。字符串是最明显的差异之一。 Python 3 更合乎逻辑,Python 2.6 现在更常用。 Python 2.7 介于两者之间。
【解决方案2】:

结尾的L 表示您有一个long。你实际上总是有它,但是printing a dict 将显示值的可打印表示,包括L 符号;但是,打印 long 本身只显示数字。

几乎可以肯定,您不必担心删除尾随的L;您可以在所有计算中使用long,就像使用int 一样。

【讨论】:

    【解决方案3】:

    pepr 的回答是对的,但如果你真的需要,你可以使用 int() 函数,它也适用于大整数

    Python 2.7.3 (default, Jul 24 2012, 10:05:39) 
    [GCC 4.7.0 20120507 (Red Hat 4.7.0-5)] on linux2
    >>> import os
    >>> os.path.getsize('File3')
    4099L
    

    但是如果你自动输入函数 int():

    >>> int(os.path.getsize('File3'))
    4099
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多