当前位置: 移动技术网 > IT编程>脚本编程>Python > python中文件操作的其他方法

python中文件操作的其他方法

2018年12月29日  | 移动技术网IT编程  | 我要评论

极速之巅,佳能打印机故障,玉林市

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

首先创建一个文件poems:

p=open('poems','r',encoding='utf-8')
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










 
 
 

 

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网