python 每次读两行文本
- 方法一:enumerate()函数获得行号,用行号取余;
import time
import itertools
start1=time.perf_counter()
List1=[]
path = r"C:\Users\xx.csv"
with open(path) as f:
for lineID, line in enumerate(f):
if lineID % 2 == 0:
List1.append(line)
if lineID % 2 == 1:
List1.append(line)
f.close()
print("time used= ", time.perf_counter()-start1)
- 方法二
- itertools.zip_longest(*iterables, fillvalue=None)
Make an iterator that aggregates elements from each of the iterables. If the iterables are of uneven length, missing values are filled-in with fillvalue. Iteration continues until the longest iterable is exhausted.
聚合多个迭代对象,长度为最长的对象。
start2 = time.perf_counter()
List2 = []
with open(path) as f:
for line1, line2 in itertools.zip_longest(*[f]*2):
List2.append(line1)
List2.append(line2)
f.close()
print("time used= ",time.perf_counter() -start2)
- 方法三:
start3 = time.perf_counter()
List3 = []
with open(path) as f:
while True:
line1=f.readline()
line2=f.readline()
if not line2:
break
List3.append(line2)
f.close()
print("time used= ", time.perf_counter() - start3)
参考:
https://docs.python.org/3.8/library/itertools.html?highlight=itertools%20zip_longest#itertools.zip_longest