估计文件中的行数文件大小和所有行的大小不匹配

2024-06-07 01:08:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我有几百个文件,每个文件的大小在10s MB到几GB之间,我想估计行数(即不需要精确的计数)。每一行都是非常规则的,例如4个long int和5个double float。在

我试图找到文件中第一个AVE_OVER行的平均大小,然后用它来估计总行数:

nums = sum(1 for line in open(files[0]))
print "Number of lines = ", nums

AVE_OVER = 10
lineSize = 0.0
count = 0
for line in open(files[0]):
    lineSize += sys.getsizeof(line)
    count += 1
    if( count >= AVE_OVER ): break

lineSize /= count
fileSize = os.path.getsize(files[0])
numLines = fileSize/lineSize
print "Estimated number of lines = ", numLines

这个估计有点离谱:

^{pr2}$

因此,我尝试计算文件中所有行的总大小,并与sys测量的大小进行比较:

fileSize = os.path.getsize(files[0])
totalLineSize = 0.0
for line in open(files[0]):
totalLineSize += sys.getsizeof(line)

print "File size = %.3e" % (fileSize)
print "Total Line Size = %.3e" % (totalLineSize)

但这些又是不一致的!在

> File size = 3.366e+07
> Total Line Size = 5.236e+07

为什么每行的大小之和比实际的文件总大小大得多?我该怎么纠正呢?


编辑:我最终得到的算法(2.0版);感谢@J.F.Sebastian

def estimateLines(files):
    """ Estimate the number of lines in the given file(s) """

    if( not np.iterable(files) ): files = [files]
    LEARN_SIZE = 8192

    # Get total size of all files                                                                                                                                                                   
    numLines = sum( os.path.getsize(fil) for fil in files )

    with open(files[0], 'rb') as file:
         buf = file.read(LEARN_SIZE)
         numLines /= (len(buf) // buf.count(b'\n'))

    return numLines

Tags: 文件ofinforcountlinefilesopen
2条回答

要估计文件中的行数:

def line_size_hint(filename, learn_size=1<<13):
    with open(filename, 'rb') as file:
        buf = file.read(learn_size)
        return len(buf) // buf.count(b'\n')

number_of_lines_approx = os.path.getsize(filename) // line_size_hint(filename)

要找到确切的行数,可以use ^{} script

^{pr2}$

sys.getsizeof是这里问题的唯一原因。它提供了任意大小的依赖于实现的对象,除了非常罕见的情况外,根本不应该使用。在

只需以二进制文件的形式打开文件,并使用len获得行的实际长度。在

相关问题 更多 >