打开文件:

fobj = open(filename, 'r')
for eachLine in fobj:
    print eachLine,  #由于每行自带一个换行符,所以print后面有逗号,阻止print再换行
fobj.close()        #已打开的文件,访问结束之后,记得close

  其中,filename是文件的字符串名字;'r'为访问模式,表示读(read)文件,其他模式还有 'w':写文件,'a':添加,'+':读写,'b':二进制访问;未提供访问模式时,默认为'r'。打开成功时返回一个文件对象句柄。

  上述程序,一次读入了所有行(适用于小文件),迭代输出各行,然后关闭文件。

  file()函数功能等同于open(),是一个工厂函数,生成文件对象。(类似于int()生成整形对象)

17 异常

  可以用try...except来检测和处理异常

try:
   #可能出错的代码
  ...
except XError, e:   print 'error', e  
#捕获异常XError,并输出异常信息e

18 函数

  函数定义:

def addMe2Me(x):                      #def 函数名(参数列表):   记得冒号
    'apply + operation to argument'   #函数说明文档
    return (x + x)                    #返回,如果没有return,自动返回None对象    

  函数调用:

>>> addMe2Me(4.25)
8.5
>>> addMe2Me('Python')    #字符串相加
'PythonPython'
>>> addMe2Me([-1, 'abc'])  #列表相加
[-1, 'abc', -1, 'abc']

  默认参数:

>>> def foo(debug=True):    #默认参数
...   'determine if in debug mode with default argument'
...   if debug:
...     print 'in debug mode'
...   print 'done'
...
>>> foo()  #未提供参数,默认为True
in debug mode
done
>>> foo(False)  #显示提供参数,覆盖默认
done

19 类

  定义类:

class FooClass(object):  #定义类用class关键字,括号里是基类,如果没有合适基类就使用object作为基类
  """my very first class: FooClass"""   #类文档,可选
  version = 0.1                #静态变量,为所有成员函数共享

  #创建类实例后,自动执行该函数;显示定义该函数,覆盖默认的init函数(什么也不做);所有的__fun__都是特殊方法。
  def__init__(self, nm='John Doe'):    #self参数,即类实例自身的引用    
    """constructor"""
    self.name = nm     #name,类实例的属性,不是类本身的部分
    print'Created a class instance for', nm

  def showname(self):
    """display instance attribute and class name"""
    print 'Your name is', self.name
    print 'My name is', self.__class__.__name__ #该变量表示实例化该实例的类的名字,self.__class__引用实际的类
  def showver(self):     """display class(static) attribute"""     print self.version  #访问静态变量      def addMe2Me(self, x): #没有使用self     """apply + operation to argument"""     return x + x

  创建类实例:

>>> foo1 = FooClass()  #自动调用__init__
Created a class instance for John Doe

  方法调用:

>>> foo1.showname() 
Your name is John Doe  #打印定义时的默认参数
My name is __main__.FooClass  
>>> foo1.showver()
0.1
>>> print foo1.addMe2Me('xyz')
xyzxyz

  提供参数:

>>> foo2 = FooClass('Jane Smith') 
Created a class instance for Jane Smith
>>> foo2.showname()
Your name is Jane Smith
My name is FooClass  #与上不同

20 模块

  模块,就是一个Python源文件,模块名就是文件名去掉后缀.py,模块包括可执行代码/函数/类。

  导入模块,访问模块属性:

>>> import sys
>>> sys.stdout.write('Hello World!\n')  #访问函数,write函数需要显示提供\n来输出换行
Hello World!
>>> sys.platform  #访问变量
'linux2'

21 有用的函数

dir([obj])     #显示对象的属性,如果没有提供参数,则显示全局变量的名字
help([obj])    #以一种整齐美观的形式显示对象的文档字符串,如果没有提供任何参数,则会进入交互式帮助
int(obj)       #将一个对象转换为整数
len(obj)       #返回对象的长度
open(fn, mode)   #以 mode('r' = 读,'w'= 写)方式打开一个文件名为fn的文件
range([start,]stop[,step]) #返回一个整数列表。起始值为 start,结束值为 stop-1;start默认值为0,step默认值为1
raw_input(str)   #等待用户输入一个字符串,可以提供一个可选的参数str用作提示信
str(obj)        #将一个对象转换为字符串
type(obj)       #返回对象的类型(返回值本身是一个type对象!)

 

练习题

2-9 循环和运算符 创建一个包含五个固定数值的列表或元组,输出他们的平均值。本练习的难点之一是通过除法得到平均值。你会发现整数除会截去小数,因此你必须使用浮点除以得到更精确的结果。float()内建函数可以帮助你实现这一功能。  

1 myList = [1,2,3,5,7]
2 total = 0
3 for num in myList:
4     total += num
5 print total/5
6 print float(total)/5  #整数会执行地板除,用float()函数将其转换为浮点数
2-9 View Code

相关文章:

  • 2022-12-23
  • 2021-09-17
  • 2021-09-03
  • 2022-02-25
  • 2022-12-23
  • 2021-11-24
  • 2021-08-14
  • 2021-08-04
猜你喜欢
  • 2022-12-23
  • 2021-10-30
  • 2021-12-13
  • 2022-01-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案