最近需要处理一个文件中的所有连续行的数据内容
import os
import linecache
#f = open('myout')
count = len(open('myout').readlines())
#last_pos = f.tell() # get to know the current position in the file
#f.seek(last_pos)
#fst_line=f.readline()
#last_pos = last_pos + 1
#sec_line=f.readline()
#last_pos = last_pos + 1
#print fst_line.split(" ")[0]
#print sec_line.split(" ")[0]
#f.close()
for i in range(count-1):
fst_line=linecache.getline('myout',i)
sec_line=linecache.getline('myout',i+1)
print fst_line.split(" ")[0]
print sec_line.split(" ")[0]
#with open('myout') as f:
# for line in f:
# last_pos = f.tell()
# fst_line=line
# sec_line=line[1]
# print fst_line
# print sec_line
本文介绍了一种利用Python处理文件中连续行数据的高效方法,通过使用`linecache`模块来读取文件内容,从而避免了传统方法中的多次文件操作,显著提高了性能。
4038

被折叠的 条评论
为什么被折叠?



