简体   繁体   English

使用readline读取txt文件python3

[英]Use readline to read txt file python3

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? 我的问题是如何使用函数.readline()来读取文本文件的结尾? I know that .readlines() work as well but I'm trying to process one line at a time. 我知道.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? 我的问题是,当我运行它时,我得到一个无限循环,一旦它不能再读取一行就不应该停止吗?

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 with statement 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 with block, the fileobj will be released on an exception or when the block ends. 关于你的意图更清楚,并且通过使用with块,fileobj将在异常或块结束时释放。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM