前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >python操作文本

python操作文本

作者头像
py3study
发布2020-01-13 13:00:32
5830
发布2020-01-13 13:00:32
举报
文章被收录于专栏:python3python3python3

python打开一个文件的句柄用open()

>>> d = open('a.txt','w') #w write r read a append
>>> d.write('hi.\nsecond hi.')
>>> d.close()
>>> d=open('a.txt','r')
>>> d.readline()
'hi.\n'
>>> d.readline() #一次读一行,指针会改变
'second hi.'
>>> d.readline() #一次读一行,指针会改变
''
>>> d.seek(0) #文本的指针重置为0
>>> d.read(100) #表示一次读100个字节
'hi.\nsecond hi.'
>>> a = open('tmp.txt','w') #文件不存在会自动创建
>>> a.write(1) #只能写字符串或者是字符流
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
TypeError: argument 1 must be string or read-only character buffer, not int
>>> a.write("this is my apple!")
>>> a.close()
>>> b=open("tmp.txt",'r')
>>> b.read(500)
'this is my apple!'
>>> b.seek(0)
>>> b.readline()
'this is my apple!'

标准库的介绍 linecache

>>> import linecache
>>> print linecache.getline("tmp.txt",1)
this is my apple!
>>> print linecache.getline("tmp.txt",2)
hhloo 
>>> print linecache.getline("tmp.txt",3)
ni hoa 
>>> lines=linecache.getlines("tmp.txt")
>>> lines
['this is my apple!\n', 'hhloo \n', 'ni hoa \n', 'hello\n', '\n']
>>> help(linecache) 查看帮助
# cat /usr/lib64/python2.7/linecache.py 查看源码
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019-08-08 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档