阅读非常大的一个班轮文本文件

Mas*_*hip 6 python numbers text-files large-files python-3.x

我有一个30MB的.txt文件,与一个数据线(3000万位数字)
不幸的是,每次我试过的方法(mmap.read(),readline(),分配1GB的RAM,用于循环)需要45+分钟仔细阅读本文件.我在互联网上找到的每一种方法似乎都是因为每条线都很小,因此内存消耗量只有文件中的最大线.这是我一直在使用的代码.

start = time.clock()
z = open('Number.txt','r+') 
m = mmap.mmap(z.fileno(), 0)
global a
a = int(m.read())
z.close()
end = time.clock()
secs = (end - start)
print("Number read in","%s" % (secs),"seconds.", file=f)
print("Number read in","%s" % (secs),"seconds.")
f.flush()
del end,start,secs,z,m
Run Code Online (Sandbox Code Playgroud)

除了将数字从一行分成不同的行; 我宁愿不这样做,是否有一种更清洁的方法,不需要一个小时的大部分时间?

顺便说一句,我不一定要使用文本文件.

我有:Windows 8.1 64位,16GB RAM,Python 3.5.1

Mar*_*nen 11

读取的文件很快(<1s):

with open('number.txt') as f:
    data = f.read()
Run Code Online (Sandbox Code Playgroud)

将一个3000万字节的字符串转换为整数,这很慢:

z=int(data) # still waiting...
Run Code Online (Sandbox Code Playgroud)

如果将数字存储为原始大端或小端二进制数据,则int.from_bytes(data,'big')更快.

如果我的数学运算正确(注意_意味着Python的交互式解释器中的"最后一行答案"):

>>> import math
>>> math.log(10)/math.log(2)  # Number of bits to represent a base 10 digit.
3.3219280948873626
>>> 30000000*_                # Number of bits to represent 30M-digit #.
99657842.84662087
>>> _/8                       # Number of bytes to represent 30M-digit #.
12457230.35582761             # Only ~12MB so file will be smaller :^)
>>> import os
>>> data=os.urandom(12457231) # Generate some random bytes
>>> z=int.from_bytes(data,'big')  # Convert to integer (<1s)
99657848
>>> math.log10(z)   # number of base-10 digits in number.
30000001.50818886
Run Code Online (Sandbox Code Playgroud)

编辑:仅供参考,我的数学不对,但我修好了.感谢10个赞成票而没有注意到:^)


Mas*_*hip 1

我使用 gmpy2 模块将字符串转换为数字。

start = time.clock()  
z=open('Number.txt','r+') 
data=z.read()
global a
a=gmpy2.mpz(data)
end = time.clock()
secs = (end - start)
print("Number read in","%s" % (secs),"seconds.", file=f)
print("Number read in","%s" % (secs),"seconds.")
f.flush()
del end,secs,start,z,data
Run Code Online (Sandbox Code Playgroud)

它在 3 秒内完成,慢得多,但至少它给了我一个整数值。

感谢大家提供的宝贵答案,但是我会尽快标记这个答案。