【问题标题】:Extracting next line of text file [duplicate]提取文本文件的下一行[重复]
【发布时间】:2018-04-02 07:15:11
【问题描述】:

我正在尝试从 .txt 文件中提取特定信息。我想出了一种方法来隔离我需要的线路;但是,打印它们已被证明是有问题的。

with open('RCSV.txt','r') as RCSV:
   for line in RCSV.read().splitlines():
      if line.startswith('   THETA'):
           print(line.next())

当我使用 line.next() 时,它给了我这个错误:

"AttributeError: 'str' object has no attribute 'next'"

Here is a link to the .txt file
Here is a link to the area of the file in question

我要做的是提取以“THETA PHI”等开头的行之后的行。

【问题讨论】:

  • RCSV.read().splitlines() 返回行列表。
  • 你不能调用line.next(),不仅仅是因为字符串没有next方法,而是因为字符串只是字符串;他们不知道他们来自迭代器。你想要调用next 的东西是迭代器。如果您只是直接遍历文件(而不是将整个文件读入内存,然后将其拆分为行并将它们全部存储在一个列表中,只是为了获得文件已经给您的相同行),next(RCSV) 会做那。虽然我不确定它是否真的是你想要的(通常不是)。
  • 我昨天回答了一个非常相关的问题。 stackoverflow.com/questions/49599623/…

标签: python string file


【解决方案1】:

你可以使用next(input),如:

with open('RCSV.txt', "r") as input:
    for line in input:
        if line.startswith('   THETA'):
           print(next(input), end='')
           break

【讨论】:

    【解决方案2】:

    找到密钥后,您可以使用标志来获取所有行。

    例如:

    with open('RCSV.txt','r') as RCSV:
        content = RCSV.readlines()
        flag = False                         #Check Flag
        for line in content:
            if not flag:
                if line.startswith('   THETA'):
                    flag = True
            else:
                print(line)                  #Prints all lines after '   THETA'
    

    或者,如果您只需要以下行。

    with open('RCSV.txt','r') as RCSV:
        for line in RCSV:
            if line.startswith('   THETA'):
                print(next(RCSV))
    

    【讨论】:

    • 你确定next(RCSV) 工作正常吗?
    • 是的,它适用于 Python2.7 和 3.5
    【解决方案3】:

    你可以试试这个:

    with open('RCSV.txt','r') as RCSV:
        for line in RCSV:
            if line.startswith('   THETA'):
                next_line = RCSV.readline() # or RCSV.next()
                print(next_line)
    

    请注意,在您的下一次迭代中,line 将是next_line 之后的行。

    【讨论】:

    • 它似乎不起作用。它没有为我提供任何输出。
    • @Mike 你能发一个示例文件吗?
    【解决方案4】:

    String对象没有next属性,next是file对象的属性。所以 fileobject.next() 返回下一行,即 RCSV.next()。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-02-03
      • 2013-02-17
      • 2020-07-01
      • 1970-01-01
      • 2013-11-04
      • 1970-01-01
      • 2014-07-11
      • 1970-01-01
      相关资源
      最近更新 更多