简体   繁体   English

Python:在读取行时,`while`循环如何在python中工作?

[英]Python : How does `while` loop work in python when reading lines?

How does while loop work in python when reading lines? 在读取行时, while循环如何在python中工作?

state=True #can be set to {anyInterger,True,False}
while state:
    #do a task
    #if task done change state to exit loop

so depending on the state variable while loop is executed, and type(state) can be bool,int 所以取决于执行循环时的state变量, type(state)可以是bool,int

but to read lines from file using while as mentioned below 但读取来自使用文件行while如下所述

f=open('test.txt','r')
line_data=[]
line=f.readline()
while line:
    line_data.append(line)
    line=f.readline()
f.close()

after reading all lines finally line='' but type('') is str 在读完所有行后最后是line=''但是type('')str

So how did while loop terminate? 那么while循环是如何终止的呢?

I knew this could be done better using with and for , reason for not using while loop for this purpose would be helpful 我知道这可以更好地使用withfor ,因为没有使用while循环为此目的会有所帮助

There are a few implicit boolean conversions in Python. Python中有一些隐式的布尔转换。
1) bool(0) evaluates to False, any other integers evaluate to True 1) bool(0)计算结果为False,任何其他整数计算结果为True
2) bool('') , bool([]) , bool({}) also evaluate to False . 2) bool('')bool([])bool({})也评估为False This is useful to test whether a container has any items in it (non-empty strings, lists, dicts etc. evaluate to True ) 这对于测试容器中是否有任何项目非常有用(非空字符串,列表,字符串等等。评估为True

So in your case readline read the empty string, which got implicitly turned to bool and evaluated to False , therefore the loop has terminated 所以在你的情况下readline读取空字符串,它被隐式转为bool并计算为False ,因此循环终止

Whenever you use a variable as a condition to an if or a while loop it is evaluated as a boolean value. 无论何时使用变量作为ifwhile循环的条件,它都被计算为布尔值。 In Python an empty string is treated as False , therefore the while loop terminates. 在Python中,空字符串被视为False ,因此while循环终止。

reason for not using while loop for this purpose would be helpful 为此目的不使用while循环的原因会有所帮助

You should ask for a reason to use a while loop for this purpose. 您应该要求为此目的使用 while循环的原因。

Compare this: 比较一下:

f = open('test.txt','r')
line_data = []
line = f.readline()
while line:
    line_data.append(line)
    line = f.readline()
f.close()

To that: 为此:

with open('test.txt','r') as f:
     lines = f.readlines()

f.readline() is a generator object that returns '' at the end of the file. f.readline()是一个生成器对象,它在文件末尾返回'' But '' has a falsy value: 但是''有一个虚假的价值:

>>> f.readline()
''
>>> bool('')
False

Hence, when the while evaluates the line at EOF (End Of File), the value is the same as False . 因此,当while评估EOF(文件结束)时的行时,该值与False相同。

The following values are considered False (see the docs ): 以下值被视为False (请参阅文档 ):

 None False zero of any numeric type, for example, 0, 0L, 0.0, 0j. any empty sequence, for example, '', (), []. any empty mapping, for example, {}. instances of user-defined classes, if the class defines a __nonzero__() or __len__() method, when that method returns the integer zero or bool value False 

Empty string is treated as False in python. 在python中,空字符串被视为False So, it won't enter the loop. 所以,它不会进入循环。 FYI the better way of looping over the lines is 仅供参考,更好的循环方式是

line_data = []
for line in f.readlines():
    line_data.append(line)

You can even do like this also. 你甚至可以这样做。

with open('test.txt', 'r') as f:
    line_data = [line for line in f.readlines()

You can add: 你可以加:

if len(line) < 2:
    break

or alternatively: 或者:

if line == "''":
    break

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

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