python2 5 day
>>> f=open('C:\\xd.txt') >>> f.read() 'hi,sir\nwelcome to here \n' >>> f.read() '' >>> f.read() '' >>> f.seek(2,0) >>> f.read() ',sir\nwelcome to here \n' >>> f.tell() 26L >>> f.seek(0,0)//#相当于把鼠标指针移动到文件开始位置 >>> f.tell()#打印鼠标指针在文件中的位置 0L >>> f=open('C:\\test.txt')#该文件不存在,故无法打开,我的目的是创建此文件 Traceback (most recent call last): File "<pyshell#172>", line 1, in <module> f=open('C:\\test.txt') IOError: [Errno 2] No such file or directory: 'C:\\test.txt' >>> f=open('C:\\test.txt','w')#创建此文件,并准备写入 >>> f.write("see you")#书写入缓冲区 >>> f.close()#关闭文件,数据从缓冲区写入硬盘
>>> f= open("C://test.txt") >>> data = f.read() >>> f.close() >>> f= open("C://test.txt") >>> try: data = f.read() finally: f.close() #除了有更优雅的语法,with还可以很好的处理上下文环境产生的异常。 >>> with open("C://test.txt") as f: data = f.read()
Pickle(腌制,和虚拟机的快照类似)的两个常用方法:dump、load
>>> import pickle >>> mylist=[1,2,'hi',['world']]#要腌制的数据 >>> f=open('mylist.pkl','wb')#以二进制写入方式创建一个文件对象 >>> pickle.dump(mylist,f)#把数据dump进f文件 >>> f.close())#将数据从缓冲区写入硬盘 >>> f=open('mylist.pkl','rb')#以二进制读方式打开一个文件对象 >>> mylist2=pickle.load(f)#把数据从文件load >>> mylist2 [1, 2, 'hi', ['world']] >>> f.close()
Python对象别名的引用
当一个对象有多个引用的时候,并且引且有不同的名称,我们称这个对象有别名(aliase)。
如果有别名的对象是可变类型的,那么对一个别名的修改就会影响到另一个
>>> a=[1,2,3] >>> b=a >>> b [1, 2, 3] >>> a[0]=0 >>> a [0, 2, 3] >>> b [0, 2, 3]
>>> a='ba' >>> b=a >>> b 'ba' >>> b='cd' >>> b 'cd' >>> a 'ba'
__str__
当print的时候,默认调用内建函数__str__
>>> class a: def __str__(self): return "__str__" def __init__(self): print "__init__" #__init__方法不能返回值 >>> a1=a() __init__ >>> print a1#print自动调用__str__ __str__
谢谢