【问题标题】:How to move the cursor to a specific line in python如何将光标移动到python中的特定行
【发布时间】: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


【解决方案1】:

这行得通吗?如果您不想使用.readlines() 读取整个文件,可以通过调用.readline() 跳过一行。这样,您可以多次调用readline(),将光标向下移动,然后返回下一行。另外,我不建议使用line != '&lt;end&gt;\n',除非您绝对确定&lt;end&gt; 之后会有换行符。相反,请执行 not '&lt;end&gt;' in line:

之类的操作
def create_list(pos):
    list_created = []
    with open('text_file.txt', 'r') as f:
        for i in range(pos):
            f.readline()
        line = f.readline()  #And here I read the first line
        while not '<end>' in line:       
            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

text_file.txt:

Something
<start>
MY FIRST LINE
MY SECOND LINE
<end>

输出:

[['MY', 'FIRST', 'LINE'], ['MY', 'SECOND', 'LINE']]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-08-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多