语法如下:
ile_object = open(file_name, access_mode='r', buffering=-1)
read(): 直接读取字节到字符串中,最多读取给定数目个字节,默认为-1(读取至末尾)
readline(): 读取打开文件的一行,默认参数-1为读取整行,如果提供size不为-1,则返回size的不完整行。
readlines(): 读取所有的行,生成一个列表
实例如下:
In [79]: with open('test.txt', 'w') as fobj: ....: fobj.write('hello world\n') ....: fobj.write('i love this world\n') ....: fobj.write('and i love python too\n') ....: In [80]: with open('test.txt') as fobj: ....: fobj.read() ....: In [81]: fobj = open('test.txt') In [82]: fobj.read() Out[82]: 'hello world\ni love this world\nand i love python too\n' In [83]: fobj.close() In [91]: fobj = open('test.txt') In [92]: for i in range(4): ....: print fobj.readline() ....: hello world i love this world and i love python too In [93]: fobj.close() In [94]: fobj = open('test.txt') In [95]: lst = fobj.readlines() In [96]: lst Out[96]: ['hello world\n', 'i love this world\n', 'and i love python too\n']实际上用迭代文件最方便:
In [98]: fobj = open('test.txt') In [99]: for line in fobj: ....: print line ....: hello world i love this world and i love python too
file.closed: True表示文件已经关闭,否则为False
file.encoding: 文件所使用的编码
file.mode: 文件打开时使用的访问模式
file.name: 文件名
func(positional_args, keyword_args, *tuple_grp_nonkw_args, **dict_grp_kw_args)positional_args:标准的位置参数
keyword_args:关键字参数
tuple_grp_nonkw_args:元组形式体现的非关键字参数组
dict_grp_kw_args:装有关键字参数的字典
一般来说,函数的调用参数最好只能有以下四种方式(主要混淆的地方是:关键字参数和字典会混淆,所以都是用的时候,最好不要使用关键字,看第四种方式):
第一种方式:只有标准参数和关键字参数:
func(positional_args, keyword_args)第二种方式:只有标准参数和元组:
func(positional_args, *tuple_grp_nonkw_args) >>> def func(name, *num): print("name is %s" % name) print("num is") print(num) >>> func("lcj", 1, 2, 3) name is lcj num is (1, 2, 3)备注:这里不要自作聪明的调用func("lcj", (1, 2, 3)),实际上这样元组只有一个参数:
>>> func("lcj", (1, 2, 3)) name is lcj num is ((1, 2, 3),)第三种方式:只有标准参数和字典
>>> def func(name, **dictArgs): print("name is %s" % name) for key, value in dictArgs.items(): print("key is %s, value is %s" % (key, value)) >>> func("lcj", x = 1, y = 2) name is lcj key is x, value is 1 key is y, value is 2第四种方式:全部使用,但是关键字中默认值不提供:
>>> def func(num, age=25, name="lcj", *tupleArgs, **dictArgs): print("num is:%d" % num) print("name is:%s, age is:%d" % (name, age)) print("tuple Args is") print(tupleArgs) for key, value in dictArgs.items(): print("key is:%s, value is:%s" % (key, value)) >>> func(123, 23, "voler", 1, 2, 3, x = 1, y = 2) num is:123 name is:voler, age is:23 tuple Args is (1, 2, 3) key is:y, value is:2 key is:x, value is:1
@deco1(deco_arg) @deco2 def func(): pass<==>
func = deco1(deco_arg)(deco2(func))示例代码:
from time import ctime, sleep def tsfunc(func): def wrappedFunc(): print '[%s] %s called' % (ctime(), func.__name__) return func() return wrappedFunc @tsfunc def foo(): pass foo() sleep(4) for i in range(2): sleep(1) foo()解释器输出如下:
lcj@lcj-Vostro-3800:~$ python test.py [Sat Apr 4 18:46:00 2015] foo called [Sat Apr 4 18:46:06 2015] foo called [Sat Apr 4 18:46:07 2015] foo called
lambda的语法如下:
lambda [arg1, [, arg2, ...argN]] : expressionpython允许用lambda关键字创造匿名函数,匿名是因为不需要以标准的方式来声明.
>>> (lambda x, y : x * y)(2, 3) 6filter(func, seq):
调用一个布尔函数func来迭代遍历每个seq中的元素:返回一个使func返回值为true的元素的序列。
>>> from random import randint >>> allNums = [randint(1, 99) for i in range(9)] >>> allNums [29, 3, 67, 81, 13, 36, 64, 92, 4] >>> print(list(filter(lambda x : x % 2, allNums))) [29, 3, 67, 81, 13]
map(func, seq1[,seq2...]):
将函数func作用域给定序列(s)的每个元素,并用一个列表来提供返回值:如果func为None,func表现为一个身份函数,返回一个含有每个序列中元素集合的n个元组的列表。
>>> print(list(map(lambda x, y : x + y, (1, 2, 3), (4, 5, 6)))) [5, 7, 9]
reduce(func, seq[,init]):
将二元函数作用于seq序列的元素,每次携带一对(先前的结果以及下一个序列元素),连续的将现有的结果和下一个值作用在获得的随后的结果上,最后减少我们的序列为一个单一的返回值:如果初始值init给定,第一个比较会是init和第一个序列元素而不是序列的头两个元素
>>> import functools >>> print(functools.reduce(lambda x, y : x + y, range(5))) 10
闭包将内部函数自己的代码和作用域以及外部函数的作用结合起来.闭包的词法变量不属于全局名称空间域或者局部的--而属于其他的名称空间,带有"流浪"的作用域.(注意这不同于对象因为那些变量是存活在一个对象的名称空间但是闭包变量存活在一个函数的名称空间和作用域)
>>> def counter(start_at): def incr(): start_at[0] += 1 return start_at[0] return incr >>> count = counter([5]) >>> print(count()) 6 >>> print(count()) 7备注:这里之所以用列表因为列表可变,不能使用不可变的数据,如数值,字符串等等.
从语法上讲,生成器是一个带yield语句的函数.一个函数或者子程序只返回一次,但一个生成器能暂停执行并返回一个中间的结果--那就是yield语句的功能,返回一个值给调用者并暂停执行,当生成器的next()方法被调用的时候,它会准确的从离开地方继续.
>>> def simpleGen(): yield 1 yield "2-->punch!" >>> for i in simpleGen(): print(i) 1 2-->punch!而我们可以通过send来向生成器传递参数,用close来退出生成器:
>>> def counter(start_at = [0]): while True: val = (yield start_at[0]) if val is not None: start_at[0] = val else: start_at[0] += 1 >>> count = counter([5]) >>> print(count.__next__()) 5 >>> print(count.__next__()) 6 >>> count.send(9) 9 >>> count.__next__() 10