问题:
python有没有一种方法是比简单的readlines()方法更快的方式去读取单个文件,比如,一个从头读文件,一个从尾部读文件,再或者预先将一个文件的行索引分成几个部分来读(文件行内容的操作顺序不重要)。
纯属瞎猜,google貌似找不到关键字。多谢不吝赐教
下面是我自己根据multiprocess瞎写的一个脚本,但是会比for循环慢很多(感觉有一个进程在一个cpu croe上占用太多cpu时间)
#_*_ encoding: utf-8 _*_
'''
Created on 2016-05-10 12:35:29
@author: han
'''
import time
from multiprocessing import Pool
def for_seprate(one_list):
# result_file = open('result.txt', 'a')
tmp = []
for x in one_list:
tmp.append(x)
# print(one_list)
def main():
with open('data.txt', 'r') as f:
line = f.readlines()
#将列表分成多少份
num_of_part = 1000
line_part = len(line) / num_of_part
P = Pool()
if line_part * num_of_part == len(line):
#
line_start = 0
line_end = line_part
while line_end <= len(line):
line_copy = line[line_start:line_end]
#
# testtime = time.time()
P.apply_async(for_seprate, args=(line_copy,))
# print('''line_start : {}
# line_end : {}
# line_copy : {}'''.format(line_start, line_end, line_copy))
# print('testendtime : {}'.format(time.time() - testtime))
line_start = line_end
line_end = line_end + line_part
P.close() #关闭不再产生子进程
P.join() #等待子进程结束
# print('All subprocess done.')
if __name__ == '__main__':
StartTime = time.time()
main()
print('UseTime : {}'.format(time.time() - StartTime))
新手还请不吝赐教。
with
Bahasa menyokong mod lelaran untuk membaca fail besar.Anda boleh mencuba pelbagai benang
Rujuk di sini