发布时间:2019-08-08 07:46:20编辑:auto阅读(1269)
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 查看源码
上一篇: python读取特定的行
下一篇: python nagios plugi
48102
46789
37711
35037
29576
26237
25166
20203
19841
18315
5988°
6672°
6164°
6153°
7264°
6103°
6212°
6684°
6649°
8040°