我正在尝试读取某个目录中的一些文件,该目录中有10个文本文件。随着时间的推移,文件数量增加,现在总大小约为400MB。用Python读取大文件
文件内容的格式为:
student_name:student_ID:date_of_join:anotherfield1:anotherfield2
在匹配的情况下,我必须打印出整行。这是我尝试过的。
findvalue = "student_id" #this is users input alphanumeric
directory = "./RecordFolder"
for filename in os.listdir(directory):
with open(os.path.join(directory, filename)) as f:
for line in f:
if findvalue in line:
print line
这是有效的,但它需要很长时间。我怎样才能缩短运行时间?
如果您只读取顺序,您可以使用[内存映射文件](http://en.wikipedia.org/wiki/Memory-mapped_file)。 – 2012-08-04 15:50:57
定义很多时间:)在我的情况下,类似的例子在一个120M文件上需要大约0.392s。所以应该在400M文件上花费大约1.2秒。你的代码和我的唯一区别是,我明确地打开''r'ead-only'模式的文件。 – favoretti 2012-08-04 15:51:59
不需要5分钟左右:/对我来说 – Whiskey 2012-08-04 15:56:10