python - 如何解决按顺序将文件附加到另一个文件时的内存问题

标签 python memory python-2.7 buffer stringio

我正在运行以下脚本,以便通过在文件存在的情况下循环数月和数年来将文件附加到另一个文件,我刚刚使用更大的数据集对其进行了测试,我希望输出文件的大小约为 600mb .但是我遇到了内存问题。首先,遇到内存问题是否正常(我的电脑有 8 GB 内存)我不确定我是如何吃掉所有这些内存空间的?

我正在运行的代码

import datetime,  os
import StringIO

stored_data = StringIO.StringIO()

start_year = "2011"
start_month = "November"
first_run = False

current_month = datetime.date.today().replace(day=1)
possible_month = datetime.datetime.strptime('%s %s' % (start_month, start_year), '%B %Y').date()
while possible_month <= current_month:
    csv_filename = possible_month.strftime('%B %Y') + ' MRG.csv'
    if os.path.exists(csv_filename):
        with open(csv_filename, 'rb') as current_csv:
            if first_run != False:
                next(current_csv)
            else:
                first_run = True
            stored_data.writelines(current_csv)
    possible_month = (possible_month + datetime.timedelta(days=31)).replace(day=1)
if stored_data:
    contents = stored_data.getvalue()
    with open('FullMergedData.csv', 'wb') as output_csv:
        output_csv.write(contents)

我收到的引用:

Traceback (most recent call last):
  File "C:\code snippets\FullMerger.py", line 23, in <module>
    contents = stored_output.getvalue()
  File "C:\Python27\lib\StringIO.py", line 271, in getvalue
    self.buf += ''.join(self.buflist)
MemoryError

关于如何解决或使此代码更有效地克服此问题的任何想法。非常感谢
原子能机构

编辑1

运行 alKid 提供的代码后,我收到了以下回溯。

Traceback (most recent call last):
  File "C:\FullMerger.py", line 22, in <module>
    output_csv.writeline(line)
AttributeError: 'file' object has no attribute 'writeline'

我通过将其更改为 writelines 来修复上述问题,但我仍然收到以下回溯。

Traceback (most recent call last):
  File "C:\FullMerger.py", line 19, in <module>
    next(current_csv)
StopIteration

最佳答案

stored_data 中,您试图存储整个文件,但由于它太大,您会收到所显示的错误。

一种解决方案是每行写入文件。它的内存效率要高得多,因为您只在缓冲区中存储一行数据,而不是整个 600 MB。

简而言之,结构可以是这样的:

with open('FullMergedData.csv', 'a') as output_csv: #this will append  
# the result to the file.
    with open(csv_filename, 'rb') as current_csv:
        for line in current_csv:   #loop through the lines
            if first_run != False:
                next(current_csv)
                first_run = True #After the first line,
                #you should immidiately change first_run to true.
            output_csv.writelines(line)  #write it per line

应该可以解决您的问题。希望这对您有所帮助!

关于python - 如何解决按顺序将文件附加到另一个文件时的内存问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19720036/

相关文章:

python - 正确居中文本 (PIL/Pillow)

python - 导入错误 : No module named django

java - tomcat7 出现内存不足错误

python - 将词典列表保存到 .tsv 文件

python - 我可以使用集合理解从更大的字典列表中创建字典列表吗?

python-2.7 - 字符串与 unicode 编码 - Struct() 参数

Python无法识别请求 header 中的cookie

python - Tkinter 选项菜单 : setting the width by the longest menu item in the list

math - 为什么计算机科学中有8个和256个如此重要的数字?

c++ - string 和 int 对象或左值/右值的内存位置