gpt4 book ai didi

python - 在Python中使用for循环读取文件

转载 作者:行者123 更新时间:2023-12-01 02:56:37 25 4
gpt4 key购买 nike

要在Python中读取文件,必须首先打开该文件,然后需要一个read()函数。为什么当我们使用 for 循环读取文件行时,不需要 read() 函数?

filename = 'pi_digits.txt'
with open(filename,) as file_object:
for line in file_object:
print(line)

我已经习惯了下面的代码,显示了read要求。

for line in file_object.read():

最佳答案

这是因为 file_object 类内置了一个“iter”方法,用于说明文件如何与迭代语句(例如 for 循环)交互。

换句话说,当您说 for line in file_object 时,文件对象正在引用其 __iter__ 方法,并返回一个列表,其中每个索引都包含文件的一行.

关于python - 在Python中使用for循环读取文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44168286/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com