前面介绍过Python中文件操作的一般方法,包括打开,写入,关闭。本文中介绍下python中关于文件操作的其他比较常用的一些方法。

首先创建一个文件poems:

SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。
p=open('poems','r',encoding='utf-8')
for i in p:
print(i) 或者是
with open('poems','r+',encoding='utf-8') as f:
  for i in p:
  print(i)
 


结果如下:
hello,everyone
白日依山尽,
黄河入海流。
欲穷千里目,
更上一层楼。

1.readline   #读取一行内容

p=open('poems','r',encoding='utf-8')
print(p.readline())

print(p.readline())

结果如下:
hello,everyone


白日依山尽,

#这里的两个换行符,一个是everyone后边的\n,
一个是print自带的换行

2.readlines   #读取多行内容

p=open('poems','r',encoding='utf-8')
print(p.readlines()) #打印全部内容
结果如下:
['hello,everyone\n', '白日依山尽,\n', '黄河入海流。\n', '欲穷千里目,\n', '更上一层楼。']
p=open('poems','r',encoding='utf-8')
for i in p.readlines()[0:3]:
print(i.strip()) #循环打印前三行内容,去除换行和空格
结果如下:
hello,world
白日依山尽,
黄河入海流。


3.tell #显示当前光标位置
p=open('poems','r',encoding='utf-8')
print(p.tell())
print(p.read(6))
print(p.tell())

结果如下:
0
hello,
6
4.seek #可以自定义光标位置
p=open('poems','r',encoding='utf-8')
print(p.tell())
print(p.read(6))
print(p.tell())
print(p.read(6))
p.seek(0)
print(p.read(6))


结果如下:
0
hello,
6
everyo
hello,
5.flush
#提前把文件从内存缓冲区强制刷新到硬盘中,同时清空缓冲区。
p=open('poems1','w',encoding='utf-8')
p.write('hello.world')
p.flush()
p.close()

#在close之前提前把文件写入硬盘,一般情况下,文件关闭后
会自动刷新到硬盘中,但有时你需要在关闭前刷新到硬盘中,这时就可以使用 flush() 方法。
6.truncate #保留
p=open('poems','a',encoding='utf-8')
p.truncate(5)
p.write('tom')
结果如下:
hellotom
#保留文件poems的前五个字符,后边内容清空,再加上tom


 







 
 
 

 

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