我需要处理几个非常大的文件(每个大于90GB)。只有一小部分文件对我很重要。我想扫描文件并将必要的行写入另一个文件,所以我不需要每次运行实验时都处理这些大文件。每行大约有1000个字符。python - 处理非常大的文件(> 90GB)
我使用下面的代码:
def readFile(inputFile, outputFile):
startDate = datetime.datetime.strptime('10/06/2010 00:00:00', '%m/%d/%Y %H:%M:%S')
endDate = datetime.datetime.strptime('10/13/2010 23:59:59', '%m/%d/%Y %H:%M:%S')
total_lines = 0
with open(inputFile, 'r') as a_file:
for a_line in a_file:
total_lines += 1
id, date, content = splitLine(a_line)
datetime_object = datetime.datetime.strptime(date, '%m/%d/%Y %H:%M:%S')
if (datetime_object > startDate and datetime_object < endDate):
appendToFile(outputFile, a_line)
return total_lines
def splitLine(long_string):
values = long_string.split(",")
return values[0],values[1],values[2]
def appendToFile(outputFile, outputString):
try:
file = open(outputFile, 'a+')
file.write(outputString)
file.close()
except Exception as ex:
print("Error writing to file: " + outputFile)
return
的问题是,我每次运行该脚本时,该过程被卡住各地10.000.000th线。当我使用htop
命令时,我可以看到Python在卡住时仅使用大约8GB的RAM,并且使用的虚拟内存不断增加,然后OS在一段时间后终止该进程。
我使用了不同的文件,以及Python 2.7和3.5。我也尝试使用with open(inputFile, 'r', 16777216)
来使用缓冲,但结果没有改变。我在macOS Sierra 10.12.4上运行代码,机器有16GB的RAM。
任何想法?
'appendToFile()'做了什么?你应该包括一个完整的例子,其中包括*所有代码需要重现问题(“[mcve]”)。 – Carpetsmoker
不要在评论中发布你的代码,你可以[编辑]你的问题;-) – Carpetsmoker
@Carpetsmoker编辑:) – gokhan