MemoryError Python,在文件99999999字符串中



Windows 10 pro 64位,python 已安装 64 位版本

文件重 1,80 GB

如何修复此错误,并打印所有字符串

def count():
reg = open('link_genrator.txt', 'r')
s = reg.readline().split()
print(s)

reg.read().split('n')将给出所有行的列表。

你为什么不做s = reg.read(65536).splitlines()?这将为您提供有关内容结构的提示,然后您可以使用您在块中读取的大小。 一旦你知道更多,你可以尝试循环该

行,总结行数

在查看了答案并试图了解最初的问题可能是什么之后,我得出了比上一个更完整的答案。 查看示例函数中的问题和代码,我现在假设如下:

  • 似乎他想将文件的内容分成单词并打印出来
  • 从函数名称中我想他想数出所有这些单词
  • 整个文件非常大,因此 Python 因内存错误而停止

处理如此大的文件显然需要与通常不同的处理方式。例如,我认为在控制台上打印此类文件的所有分隔单词没有任何用处。当然,计算这些单词或在其中搜索模式可能是有意义的。

为了举例说明如何处理如此大的文件,我写了以下示例。它旨在根据您自己的要求进行进一步改进和更改的起点。

MAXSTR = 65536
MAXLP = 999999999 
WORDSEP = ';'
lineCnt = 0
wordCnt = 0
lpCnt = 0
fn = 'link_genrator.txt'
fin = open(fn, 'r')
try:
while lpCnt < MAXLP:
pos = fin.tell()
s = fin.read(MAXSTR)
lines = s.splitlines(True)
if len(lines) == 0:
break
# count words of line
k= 0
for l in lines:
lineWords = l.split(WORDSEP)# semi-colon separates each word
k += len(lineWords)         # sum up words of each line
wordCnt += k - 1                # last word most probably not complete: subtract one
# count lines
lineCnt += len(lines)-1
# correction when line ends with n
if lines[len(lines)-1][-1] == 'n':
lineCnt += 1
wordCnt += 1
lpCnt += 1
print('{0} {4} - {5} act Pos: {1}, act lines: {2}, act words: {3}'.format(lpCnt, pos, lineCnt, wordCnt, lines[0][0:10], lines[len(lines)-1][-10:]))
finally:
fin.close()
lineCnt += 1
print('Total line count: {}'.format(lineCnt))

该代码适用于最大 2GB 的文件(使用 2.1GB 测试(。开头的两个常量允许您以块为单位处理读取的大小,并限制处理的文本量。在测试期间,您可以只处理整个数据的子集,这要快得多。

最新更新