Python 之读取大文件readline与readlines的差别

时间:2022-07-03 19:31:33
import time


def get_all_lines(filename):
    start_time = time.time()
    try:
        f = open(filename, 'rb')
    except Exception as e:
        exit(e)
    f.readlines()
    f.close()
    end_time = time.time() - start_time
    print("get_all_lines:%s" % end_time)


def get_one_line(filename):
    start_time = time.time()
    try:
        f = open(filename, 'rb')
    except Exception as e:
        exit(e)
    while True:
        string = f.readline()
        if not string:
            break
    f.close()
    end_time = time.time() - start_time
    print("get_one_line:%s" % end_time)


if __name__ == '__main__':
    file_name = "des114.sql"
    get_all_lines(file_name) # 3.311237573623657
    get_one_line(file_name) # 2.696101665496826