def test1(): with open("/tmp/test.log", "r") as f: print f.read()
或者
def test2(): f = open("/tmp/test.log", "r") for line in f.readlines(): print line f.close()
def read_in_block(file_path): BLOCK_SIZE = 1024 with open(file_path, "r") as f: while True: block = f.read(BLOCK_SIZE) # 每次读取固定长度到内存缓冲区 if block: yield block else: return # 如果读取到文件末尾,则退出def test3(): file_path = "/tmp/test.log" for block in read_in_block(file_path): print block
方法二:
利用open(“”, “”)系统自带方法生成的迭代对象
def test4(): with open("/tmp/test.log") as f: for line in f: print line for line in f 这种用法是把文件对象f当作迭代对象, 系统将自动处理IO缓冲和内存管理, 这种方法是更加pythonic的方法。 比较简洁。