读取文件中的有限行可以使用以下方法:
file = open("file.txt", "r")
lines = []
for line in file:
lines.append(line)
lines = []
count = 0
for line in file:
lines.append(line)
count += 1
if count == 5:
break
file.close()
完整的代码示例:
file = open("file.txt", "r")
lines = []
count = 0
for line in file:
lines.append(line)
count += 1
if count == 5:
break
file.close()
print(lines)
注意事项:
推荐的腾讯云相关产品和产品介绍链接地址:
领取专属 10元无门槛券
手把手带您无忧上云