【问题标题】:Memory error while reading large file读取大文件时出现内存错误
【发布时间】:2018-10-13 14:40:12
【问题描述】:

我正在尝试读取一个 59 GB 的文件,并根据在每行的请求中找到的一些 id 将其分解为多个新文件。我正在运行下面的代码,该代码在生成 45GB 文件后出现内存错误。系统内存一直保持在非常低的水平,并在代码运行大约 2 小时后突然创建一个。我有 16GB 内存。我是否错误地使用了缓冲?任何想法?

outputFile = '/home/.../folder1'
directory = '/home/.../folder2/'

with open(directory + 'aldk_tab_1mn.csv', 'r', buffering=50000000) as fin: 
    firstLine = fin.readline()
    print(firstLine)

    for line in fin:
        testChar = line[0:4]
        if testChar[0] == 'A' :
            if not os.path.exists(outputFile + '/A/' + testChar+'.csv'):   # first time open a file             
                with open(outputFile + '/A/' + testChar+'.csv', 'a') as foutA:
                    print('file', testChar, 'created')                    
                    foutA.write(firstLine)
                    foutA.write(line)          
            else: 
                with open(outputFile + '/A/' + testChar+'.csv', 'a') as foutA:
                    foutA.write(line)          
        else:
            if not os.path.exists(outputFile + '/B/' + testChar+'.csv'):   # first time open a file             
                with open(outputFile + '/B/' + testChar+'.csv', 'a') as foutB:
                    print('file', testChar, 'created')
                    foutB.write(firstLine)
                    foutB.write(line) 
            else: 
                with open(outputFile + '/B/' + testChar+'.csv', 'a') as foutB:
                    foutB.write(line)   

产生的错误是

MemoryError                               
Traceback (most recent call last)
 <ipython-input-17-761f2fcce982> in <module>()
  6 
----> 7     for line in fin:
  8         testChar = line[0:4]
  9         if testChar[0] == 'A' :

MemoryError: 

【问题讨论】:

  • 这可能会有所帮助:stackoverflow.com/a/14268804/4737952
  • 您的问题是否存在于您阅读的大文件中的一个令人惊讶的长行中?在这种情况下,最好不要一次遍历完整的行。
  • 您是否尝试过移除缓冲?顺便说一句,您可以修复问题中的拼写错误吗?很难读。
  • @Martijn 好点。如果由于缺少行终止符而突然一条线长为 50GB,那么 OP 的祝酒词。这一定是问题所在......在这种情况下,逐个字符读取字符是解决方案,但 OP 输入可能已损坏......
  • 您可以尝试降低缓冲区。 50MB 对我来说似乎很高。说到缓冲区,您可能还想拥有写缓冲区。这样您就不会在每次要写下一行时都打开写入+关闭写入。

标签: python out-of-memory large-data


【解决方案1】:

感谢您的回复,文件似乎在某个点之后有空字符,使得 line 变量按照@Martijn 的建议爆炸!

所以我确实对我的文件进行了切片!谢谢大家!

【讨论】:

    猜你喜欢
    • 2020-03-19
    • 1970-01-01
    • 2021-10-29
    • 2020-02-21
    • 2017-10-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多