我正在运行以下脚本,以便通过循环数月和数年(如果文件存在)将文件彼此附加,我刚刚使用更大的数据集对其进行了测试,我预计输出文件的大小约为 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
如何解决此问题或使此代码更有效地克服此问题的任何想法。非常感谢
AEA
编辑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