前面介绍过Python中文件操做的通常方法,包括打开,写入,关闭。本文中介绍下python中关于文件操做的其余比较经常使用的一些方法。python
首先建立一个文件poems:spa
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
白日依山尽,
黄河入海流。
欲穷千里目,
更上一层楼。
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