文件操作:
Open函数格式
handle = open(file_name, ‘r’) #open后接文件名和打开方式,‘r’:只读,‘w’:可写,‘+’:读写, 'a' 表示添加,'b'表示二进制访问。
Example:
__author__ = 'Joe' #! coding: utf-8 def write_into_file(): """向文件test.txt文件中,写入信息""" try: f_obj = open("test.txt", "w") f_str = 'a' while "q" != f_str: f_str = raw_input("输入文件内容(以q结束):") f_obj.write(f_str) f_obj.write('\n') f_obj.close() return True except IOError, e: print "异常:", e return False def read_from_file(): """从文件test.txt读取信息""" try: f_obj = open("test.txt", "r") print "test.txt 的内容:" for eachLine in f_obj: print eachLine, f_obj.close() return True except IOError, e: print '异常:', e return False def main(): write_success = write_into_file() if write_success: read_from_file() else: print "写入文件失败" #调用主函数 main()
类的定义:
__author__ = 'Joe' class FooClass(object): """my very first class: FooClass""" version = 0.1 # class (data) attribute def __init__(self, nm='John Doe'): """constructor""" self.name = nm # class instance (data) attribute print 'Created a class instance for', nm def show_name(self): """display instance attribute and class name""" print 'Your name is', self.name print 'My name is', self.__class__.__name__ def show_ver(self): """display class(static) attribute""" print self.version # references FooClass.version def addme2me (self, x): # does not use 'self' """apply + operation to argument""" return x + x my_obj = FooClass() my_obj.show_name() my_obj.show_ver()
PEP:
在本书中你会经常看到 PEP 这个字眼。 一个 PEP 就是一个 Python 增强提案(Python Enhancement Proposal), 这也是在新版 Python 中增加新特性的方式。 从初学者的角度看,它们是一些高级读物, 它们不但提供了新特性的完整描述, 还有添加这些新特性的理由, 如果需要的话, 还会提供新的语法、 技术实现细节、向后兼容信息等等。在一个新特性被整合进 Python 之前,必须通过 Python 开发社区,PEP 作者及实现者,还有 Python 的创始人,Guid ovan Rossum(Python 终身的仁慈的独裁者)的一致同意。PEP1 阐述了 PEP 的目标及书写指南。在 PEP0 中可以找到所有的 PEP。 PEP 索引的网址是: http://python.org/dev/peps。