python中怎么读取前几行数据呢
有2种方法
1.这种比较简单
n = int(input())
f=open('test.txt','r')
for i in range(n):
print(f.readline().strip())
2.这种就比较麻烦了,我觉得python最大的优点就是内置函数比较多
所以还是比较推荐第一种呀
n = int(input())
with open('test.txt') as file_object:
lines = file_object.readlines()
i = 0
for line in lines:
print(line.rstrip())
i = i+1
if i==n:
break