Python opens a handle to a file with 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 () # Reading one line at a time, the pointer changes ' second hi. ' >>> d.readline () #一次读一行, the pointer will change ' >>> d.seek (0) #文本的指针重置为0 >>> d.read #表示一次读100个字节 ' hi.\ Nsecond hi. '
>>> a = open (' Tmp.txt ', ' W ') #文件不存在会自动创建 >>> a.write (1) #只能写字符串或者是字符流Traceback (most recent): F Ile "<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 (+) ' This is my apple! ' >>> b.seek (0) >>> b.readline () ' This is my apple! '
Introduction to the standard library 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 ']>>& Gt Help (Linecache) see how-to cat/usr/lib64/python2.7/linecache.py see the source code
This article from "Small Fish Blog" blog, declined reprint!
Python action text