f=open('ceshi.txt','a',encoding='utf-8')
r=open('ceshi.txt','r',encoding='utf-8')
上面的2种写法可以用with来写:
with open
('ceshi.txt','a',encoding='utf-8') as f:
with open('ceshi.txt','r',encoding='utf-8') as r:这两个写法不需要用f.close()和r.close()

#ceshi.txt里面已经分行展示了first second third
r.seek(0)  #默认从最开始读起
r.seek(1,0)  #从最开始偏移1位开始读,
r.readline()打印出来的就是irst,而不是first
print(r.readline())  #r.readline()逐行读取数据,每执行一次,就只打印出第一行数据first
print(r.readline())  #打印出第2行的数据second
print(r.readlines())  #r.readlines()读取所有行的数据,读出来的是一个列表 如果上面2个打印都存在,则只打印出第3行数据
for line in r.readlines():  
  print(line)  #循环读出每行数据    如果上面3个打印都存在,则不会输出,因为3行数据都被输出了
r.close()

注意:如果r.readline()和readlines()同时存在的时候,如果上面的已经读出来了,下面的一个读取数据是从剩下的数据里面读的


扫码关注我们
微信号:SRE实战
拒绝背锅 运筹帷幄