例如,我需要通过调用readline10次来读取文件.
with open("input") as input_file:
for i in range(10):
line = input_file.readline()
# Process the line here
Run Code Online (Sandbox Code Playgroud)
这是一种非常常用的技术,用于range控制循环次数.唯一的缺点是:有一个未使用的i变量.
这是我从Python中获得的最好的吗?有更好的想法吗?
PS在Ruby中我们可以做到:
3.times do
puts "This will be printed 3 times"
end
Run Code Online (Sandbox Code Playgroud)
这是优雅和非常清楚地表达意图.
使用islice从itertools
from itertools import islice
with open("input", 'r') as input_file:
for line in islice(input_file, 10):
#process line
Run Code Online (Sandbox Code Playgroud)
由于您可以直接遍历文件行,因此无需调用input_file.readline()
查看itertools.islice的文档