【问题标题】:python read file next()python读取文件next()
【发布时间】:2014-09-21 18:35:12
【问题描述】:

为我糟糕的编程表示歉意,因为我是一个糟糕的程序员。我参考:How to access next line in a file(.txt) in Python 在问题实例中,next() 模块能够读取下一行。 但是,一旦代码返回到 for 循环,就不会是“下一行”而是下一行了。

输入:

a /n
b /n
c /n
d /n

输出:

This line contains a, next line contains b.
This line contains c next line contains d.

有没有可能达到这样的结果

This line contains a, next line contains b
This line contains b next line contains c

编辑-抱歉忘记输入代码-示例代码:

a = open('file.txt','rb')
for i in a:
 b = next(a)
 print "this line contains %s, next line contains %s" %(a,b)
 a.close()

【问题讨论】:

  • 向我们展示您尝试达到预期结果的代码。
  • 我假设发布问题的人对编程和堆栈溢出也是新手。因此,请不要只对问题投反对票,引导此人发布适当的问题并鼓励他的热情。
  • 感谢您的热心回答

标签: python next


【解决方案1】:

您可以使用文件对象的readlines 方法来制作文件行的列表。

由于每行末尾都有一个换行符,如果您希望将其打印在单行上,然后是其他一些文本,则需要将其删除。您可以使用字符串对象的strip 方法来执行此操作,该方法会删除字符串的尾随字符。

遍历行时,您可以通过将索引增加1 来访问列表中的下一行。

而且我发现在创建文件对象时最好使用with open(...) as file_name: 语法,因为它会自动为您关闭文件。

with open('file.txt', 'rb') as text_file:
    lines = [line.strip() for line in text_file.readlines()]
    for index, line in enumerate(lines):
        # Check for last line
        try:
            next_line = lines[index + 1]
        except IndexError:
            print("this line contains %s, and is the end of file." % line)
        else:
            print("this line contains %s, next line contains %s" % (line, next_line))

【讨论】:

  • 非常感谢,这正是我要找的东西
【解决方案2】:
a = open('file.txt','rb')
prev=a.next()
for i in a:
    print "this line contains %s, next line contains %s" %(prev,i)
    prev=i

a.close()

【讨论】:

    【解决方案3】:

    您可以通过将所有行读入字符串列表来解决您的问题。

    a = open('file.txt','rb')
    text_as_list = a.readlines()
    for idx in range(len(text_as_list)-1):
        print "this line contains %s, next line contains %s" %(text_as_list[idx], text_as_list[idx+1])
    a.close()
    

    【讨论】:

    • IMO 这个解决方案对于新手来说太复杂了
    • 即使不复杂,一次读取所有行也会导致大文件的性能下降。
    【解决方案4】:

    我想这样就可以了。但是,您应该考虑更改输出的顺序。通常,您希望先输出当前行,然后再输出前一行,因为这是读取文件的顺序。因此,解决方案可能有点混乱。喜欢就点个赞吧:-)

    a = open('text.txt','rb')
    
    current_line = " "
    previous_line = " "
    
    while (previous_line != ""):
    
        # In the first step, we continue and do nothing to read the next line so
        # we have both lines.
        if current_line == " " and previous_line == " ":
    
            # Get the first line.
            current_line = a.readline()
            continue
    
        # Update the lines.
        previous_line = current_line
        current_line = a.readline()
    
        # No output if the next line does not exist.
        if current_line == "":
    
            break
    
        # Output.
        print "This line contains " + previous_line[0] + ", next line contains " + current_line[0]
    
    a.close()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-01-12
      • 2018-03-04
      • 1970-01-01
      • 2021-12-22
      • 1970-01-01
      • 2017-09-15
      • 2015-01-08
      • 1970-01-01
      相关资源
      最近更新 更多