python操作文本
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 查看源码
相关文章