【问题标题】:Python: Read next line in a file in one simple line of codePython:用一行简单的代码读取文件中的下一行
【发布时间】:2013-09-21 18:51:54
【问题描述】:

正如标题所说,我想用一个简单的命令让 Python 读取文本文件的下一行。
例如这样的:

users = open("C:\\Users\\Tharix\\Desktop\\test.txt",mode="r")
line = test.readline(20)
print(line)
line.next() #Or something similar
print(line)

(PS:我不知道这有什么帮助,但我使用的是 Python 3.3.2 版本)
谢谢你:)

【问题讨论】:

    标签: python readline next


    【解决方案1】:

    只需遍历文件对象:

    with open("C:\\Users\\Tharix\\Desktop\\test.txt", mode="r") as users:
        for line in users:
           print(line)
    

    请注意,iter.next() 在 py3.x 中已重命名为 iter.__next__(),或者更好地使用 next(iter)。(这适用于 py2.7、py3.x)

    【讨论】:

    • 还有一件事,如果您要尝试自己调用FooIterator.__next__(),您实际上需要将其写为FooIterator._FooIterator_next__(),因为@987654327 调用的名称修改方式@ 前缀有效。
    • @hcwhsa 我不是这个意思,编辑:没关系,明白了
    • a = iter("hello"); a.__next__() 为我工作。仅当属性以 __ 开头且不以它结尾时,才会出现名称修改。
    • @user2802035 使用line = next(users)(这是 hcwhsa 所说的)。
    猜你喜欢
    • 1970-01-01
    • 2014-03-08
    • 2018-08-05
    • 2013-11-04
    • 2013-06-26
    • 1970-01-01
    • 2016-02-12
    • 2019-02-03
    • 1970-01-01
    相关资源
    最近更新 更多