使用readline读取txt文件python3

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28936140/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 03:55:24  来源:igfitidea点击:

Use readline to read txt file python3

pythonpython-3.xreadline

提问by Code971

I been working on this for hours and I cant get it right, any help would be appreciated! My question is how do I use the function .readline()to read until the end of a text file? I know that .readlines()work as well but I'm trying to process one line at a time.

我已经为此工作了几个小时,但我无法做到正确,任何帮助将不胜感激!我的问题是如何使用该函数.readline()读取到文本文件的末尾?我也知道这.readlines()行得通,但我正在尝试一次处理一行。

Here's what I have for my code so far:

到目前为止,这是我的代码:

    a = open("SampleTxt.txt","r")

    While True:

        a.readline()

My problem is that I get an infinite loop when I run this, shouldn't it have stopped once it couldn't read a line any more?

我的问题是当我运行这个时我得到了一个无限循环,一旦它不能再读取一行,它不应该停止吗?

回答by Jon Clements

a.readline()will return ''an empty string when no more data is available, you need to check that and then break your while, eg:

a.readline()''当没有更多数据可用时将返回一个空字符串,您需要检查它然后打破你的while,例如:

while True:
    line = a.readline()
    if not line: 
        break

If it's not purely for learning purposes then you really should be using a withstatement and for-loop to process the file, line by line:

如果不是纯粹出于学习目的,那么您确实应该使用with语句和 for 循环来逐行处理文件:

with open('SampleTxt.txt') as fin:
    for line in fin:
        pass # do something

It's more clear as to your intent, and by using the withblock, the fileobj will be released on an exception or when the block ends.

你的意图更清楚,通过使用with块,fileobj 将在异常或块结束时被释放。