python 文件读取
最基本的文件操作当然就是在文件中读写数据。这也是很容易掌握的。现在打开一个文件以进行写操作:
1. fileHandle = open ( 'test.txt', 'w' )?
fileHandle = open ( 'test.txt', 'w' )
‘w'是指文件将被写入数据,语句的其它部分很好理解。下一步就是将数据写入文件:
1. fileHandle.write ( 'This is a test.\nReally, it is.' )?
fileHandle.write ( 'This is a test.\nReally, it is.' )
这个语句将“This is a test.”写入文件的第一行,“Really, it is.”写入文件的第二行。最后,我们需要做清理工作,并且关闭文件:
1. fileHandle.close()?
fileHandle.close()
正如你所见,在Python的面向对象机制下,这确实非常简单。需要注意的是,当你再次使用“w”方式在文件中写数据,所有原来的内容都会被删除。如果想保留原来的内容,可以使用“a”方式在文件中结尾附加数据:
1. fileHandle = open ( 'test.txt', 'a' )?
2. fileHandle.write ( '\n\nBottom line.' )?
3. fileHandle.close()?
fileHandle = open ( 'test.txt', 'a' )
fileHandle.write ( '\n\nBottom line.' )
fileHandle.close()
?
4. fileHander.seek(0)
移动文件读取位置.
?
?
一个线上的例子
f = open ( 'message.id2', 'r' )idlist = []for read in f.readlines():if read.find("-")==-1:read=read[0:len(read)-1] idlist.append(read)print len(idlist)idlist = {}.fromkeys(idlist).keys()print len(idlist)w = open('idlist','w')for id in idlist:w.write(id+'\n')