我有几百个文件,每个文件的大小在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
为什么每行的大小之和比实际的文件总大小大得多?我该怎么纠正呢?
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
要估计文件中的行数:
要找到确切的行数,可以use ^{} script :
^{pr2}$sys.getsizeof
是这里问题的唯一原因。它提供了任意大小的依赖于实现的对象,除了非常罕见的情况外,根本不应该使用。在只需以二进制文件的形式打开文件,并使用
len
获得行的实际长度。在相关问题 更多 >
编程相关推荐