Python输入.txt文件

2024-05-26 21:54:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在独立学习Python,更具体地说是在文件I | O中

为了加载一个文本文件,我被教导使用.readline()函数,并附带以下代码。你知道吗

in_file = open (filename, "rt")

while True:
    in_line = in_file.readline ()

    if not in_line:
        break

    in_line = in_line [:-1]
    name, number = in_line.split (",")
    dic [name] = number

in_file.close ()

我正在试图理解代码是怎么回事,但我很难理解这句话:

if not in_line:
    break

我知道需要打破while循环,但它实际上是如何工作的呢?你知道吗


Tags: 文件函数代码nameinnumberreadlineif
2条回答

如果in_line为false,则没有要读取的行,则break将中断while循环,以便在文件中没有要读取的内容时程序可以结束。你知道吗

当没有更多行可读取时,^{} method返回空字符串:

When size is not 0, an empty string is returned only when EOF is encountered immediately.

条件测试该结束条件,以结束循环。^只有当in_line是空字符串时,{}才为真。Python中的所有“空”值都被认为是false,not操作符将false变成True。参见Truth Value Testing section

Any object can be tested for truth value, for use in an if or while condition or as operand of the Boolean operations below. The following values are considered false:

[...]

  • any empty sequence, for example, '', (), [].

在这里使用while循环实际上过于冗长。通过使用for循环,使文件成为迭代器,可以更简洁地读取文件:

for in_line in in_file:
    in_line = in_line.rstrip('\n')

不能保证一行以换行结束;上面的str.rstrip()调用仅当它实际在那里时才删除它。你知道吗

最后但并非最不重要的一点是,您可以将file对象用作上下文管理器;将open file对象传递给with语句可确保在执行块时,即使发生异常,文件也会再次自动关闭:

with open(filename, "rt") as in_file:
    for in_line in in_file:
        in_line = in_line.rstrip('\n')

不再需要单独的in_file.close()调用。你知道吗

另请参见教程中的Methods of File Objects section。你知道吗

相关问题 更多 >

    热门问题