【发布时间】:2022-01-13 01:35:54
【问题描述】:
我正在从 .txt 文件中读取数据。我需要从某一行开始读取行,因此我不必读取整个文件(使用 .readlines())。因为我知道我应该从哪一行开始阅读,所以我想出了这个(虽然它不起作用):
def create_list(pos):
list_created = []
with open('text_file.txt', 'r') as f:
f.seek(pos) #Here I want to put the cursor at the begining of the line that I need to read from
line = f.readline() #And here I read the first line
while line != '<end>\n':
line = line.rstrip('\n')
list_created.append(line.split(' '))
line = f.readline()
f.close()
return list_created
print(create_list(2)) #Here i need to create a list starting from the 3rd line of my file
我的文本文件看起来像这样:
Something #line in pos= 0
<start> #line in pos= 1
MY FIRST LINE #line in pos= 2
MY SECOND LINE #line in pos= 3
<end>
结果应该是这样的:
[['MY', 'FIRST', 'LINE'], ['MY', 'SECOND', 'LINE']]
基本上,我需要从特定行开始我的 readline()。
【问题讨论】:
-
如果您使用
with open打开文件,则不需要f.close() -
谁告诉你
f.seek(pos)跳过pos行? -
我应该将
pos作为参数传递给readline()方法以从第3 行开始读取吗? -
如果您还没有了解基本知识。为什么你这么关心性能?请让应用程序正常工作(只是 readlines),然后尝试提高性能。
标签: python text-files readline