python基础-4 函数参数引用、lambda 匿名函数、内置函数、处理文件

上节课总结

1、三元运算
name=“name1”if 条件 else “name2”
2、深浅拷贝
  数字、字符串
      深浅,都一样
2、其他
  浅拷贝:只拷贝第一层
  深拷贝:不拷贝最后一层
3、set集合
    无序,不重复
    交集、并集、差集、各种集
4、函数
  1、def
  2、函数名,参数
  3、功能
  4、返回值
 
参数
    普通参数
    指定参数
    默认参数,默认参数只能放到最后面
    动态参数
        *args》=元组
        **kwargs》=列表
全局变量
    global
********************************************************************

作业总结

1、判断对象是否属于某个类 对应题:比如 列表有个数字,但是循环列表就判断长度,用len 会报错。 因为int不支持len ,所以先判断 属于某类,再进行if判断。
isinstance
1 # isinstance(对象,类名) 判断变量输入的对象是否是属于这个类
2 # 方法1:
3 temp = [11, 22, "", " ", []]
4 print(isinstance(temp, (str, list, tuple)))  # 一旦对象属于这个后面元组的类中的任何一个 就返回true
5 # 方法2:
6 a = type(temp) is list
7 print(a)

2、参数引用

python中 函数传参,传引用 ,形参其实是指针映射到 实际参数的的内存地址中的。一旦更改形参对应的值,实际参数也会改。

1、函数传参数,传的是个引用,修改 或删除形参的 值 ,实际参数值也变化

1 def func(args):
2     args.append(123)
3 li=[11,22]
4 func(li)
5 print li
6 
7 C:\Python27\python2.exe E:/py/55/learn-python/oldboy/4/test.py
8 [11, 22, 123]

2、形式参数 赋值 另开辟内存

尽管 传入实际参数 li 使得 args =li ,但是 函数主体 args=123 重新赋值 相当于args重新开辟了一段 内存空间,而原li还是原来的值 如果是同一个变量名 重新赋值,原来占用内存的那个 变量空间 python会定时回收。

 1 赋值   尽管 函数调用时候 args=li 但是重新赋值,等于申请了新的内存空间。
 2 def func(args):
 3 
 4   args=123
 5 
 6 li=[1,2,3,4]
 7 a=func(li)
 8 print(li)
 9 
10 #结果 [1,2,3,4]

 1、lambda匿名函数

 

 

 1 # lambda 匿名函数
 2 
 3 def f1(ar1, ar2):
 4     return ar1 + ar2
 5 
 6 
 7 f2 = lambda ar3, ar4: ar3 + ar4
 8 
 9 ret = f2(3, 4)
10 print(ret)

学习条件运算时,对于简单的 if else 语句,可以使用三元运算来表示,即:

1 # 普通条件语句
2 if 1 == 1:
3     name = 'wupeiqi'
4 else:
5     name = 'alex'
6     
7 # 三元运算
8 name = 'wupeiqi' if 1 == 1 else 'alex'

对于简单的函数,也存在一种简便的表示方式,即:lambda表达式

 1 # ###################### 普通函数 
 2 # 定义函数(普通方式)
 3 def func(arg):
 4     return arg + 1
 5     
 6 # 执行函数
 7 result = func(123)
 8     
 9 # ###################### lambda 
10     
11 # 定义函数(lambda表达式)
12 my_lambda = lambda arg : arg + 1
13     
14 # 执行函数
15 result = my_lambda(123)

2、python的内置函数

注:查看详细猛击这里

 1 大部分函数

abs()返回一个数字的绝对值。如果给出复数,返回值就是该复数的模。

1 >>>print abs(-100)
2 >>>print abs(1+2j)
3 2.2360679775
4 # 内置函数:
5 # 1 abs() 绝对值
6 a = 123
7 b = -123
8 print(abs(a))
9 print(abs(b))

all()所有为真才为真,只要有一个假就是假
判断假的条件:
任何一种都为假: 0 None 空值(字符串 列表 元组 字典) 

1 li = [1, 2, 3, "", False]
2 print(all(li))
3 ----
4 C:\Python35\python3.exe E:/py/55/learn-python/oldboy/4/build_in_test.py
5 False

any() 一个为真就为真 同all相反,只有有真就返回True 真: 非0 非None 非空

li = [1, 2, 3, "", False]
print(any(li))
----
C:\Python35\python3.exe E:/py/55/learn-python/oldboy/4/build_in_test.py
True

ascii() 用法:ascii(对象) ===去类中找 __repr__ 方法,获取返回值,2版本中没有

 

 1 class Foo(object):
 2     def __repr__(self):
 3         return "hello repr"
 4 
 5 
 6 li = Foo()
 7 n = ascii(li)
 8 print(n)
 9 
10 ----
11 C:\Python35\python3.exe E:/py/55/learn-python/oldboy/4/build_in_test.py
12 hello repr

bin oct int hex 二进制 八进制 十进制 十六进制

 1 # bin() 可以将 八 十 十六 进制 转换成二进制
 2 print(bin(10), bin(0o13), bin(0x14))
 3 # oct() 可以将 二 十 十六 进制 转换为八进制
 4 print(oct(10), oct(0b101), oct(0x14))
 5 # int() 可以将 二 八 十六进制转换为十进制
 6 print(int(0o13), int(0b101), int(0x14))
 7 # hex() 可以将 二 八 十 进制转换为十六进制
 8 print(hex(0b101), hex(110), hex(0o12))
 9 
10 
11 print(int("0b1011", base=2))  # 必须是字符串,可以不带o b x .base= 对应的原来进制
12 print(int("72", base=8))
13 print(int("ac1", base=16))

bool 判断真假

# 什么是假的。False,0,None,"",[],(),{},用bool值.
print(bool(0), bool(None), bool(-1), bool("123"), bool(""))
>>>bool(False)
False
>>>bool("False")
True

看到上面的结果了没?是True。突然记起Python中除了''、""、0、()、[]、{}、None为False之外,其他的都是True。也就是说上面的'False'就是一个不为空的字符串,所以结果就为True了

将一个值转化成布尔值,使用标准的真值测试例程。如果x为假或者被忽略它返回False否则它返回Truebool也是一个类,它是int的子类。bool不能被继承。它唯一的实例就是FalseTrue

bytes bytearray 字节列表

byte在前面已经介绍过了 bytes('str',encoding='')      bytearray([source[, encoding[, errors]]])

1 返回一个新的字节数组。bytearray类型是一个可变的整数序列,整数范围为0 <= x < 256(即字节)。 它有可变序列的大多数方法,参见Mutable Sequence Types,同时它也有str类型的大多数方法,参见String Methods。
2 
3 source参数可以以不同的方式来初始化数组,它是可选的:
4 
5 如果是string,必须指明encoding(以及可选的errors)参数;bytearray()使用str.encode()将字符串转化为字节数组。
6 如果是integer,生成相应大小的数组,元素初始化为空字节。
7 如果是遵循buffer接口的对象,对象的只读buffer被用来初始化字节数组。
8 如果是iterable,它的元素必须是整数,其取值范围为0 <= x < 256,用以初始化字节数组。
9 如果没有参数,它创建一个大小为0的数组。

chr ord 转换 ascii对应的字符与十进制整数转换 可以百度 ascii 对照表

返回一个单字符字符串,字符的ASCII码为整数i。例如,chr(97)返回字符串'a'。 它是ord()的逆运算。参数的取值范围为[0..255]的闭区间;如果i超出取值范围,抛出ValueError参见unichr()

 1 # chr() 接收一个十进制数字,找到这个数字对应的ASCII码中对应的字符
 2 # ord() 接收一个字符,找到ASCII码种对应的十进制数字
 3 # 一个字节8位,2**8,ASCII码,256种。验证码
 4 print(chr(78))
 5 print(ord("A"))
 6 
 7 ----
 8 C:\Python35\python3.exe E:/py/55/learn-python/oldboy/4/build_in_test.py
 9 N
10 65
 1 #验证码
 2 import random
 3 temp = ''
 4 for i in range(4):
 5     num = random.randrange(0, 4)  # 生成0-4的随机数
 6     if num == 3 or num == 1:  # 如果随机数是1或3,那么在验证码中就生成0-9的随机数
 7         rad1 = random.randrange(0, 10)
 8         temp += str(rad1)  # 字符串转换拼接
 9     else:
10         rad2 = random.randrange(65, 91)  # 否则验证码中产生字母,范围是65-90
11         temp += chr(rad2)
12 print(temp)

 

callable(object检查某个对象是否可以被执行 即 对象(),后面能够加括号,去执行一段代码,就是可以执行的

如果object参数可调用,返回True;否则返回False如果返回真,对其调用仍有可能失败;但是如果返回假,对object的调用总是失败。注意类是可调用的(对类调用返回一个新实例);如果类实例有__call__()方法,则它们也是可调用的。

classmethod 后面讲 重要

compile 编译 默认读文件都是字符串,经过编译变成代码

hasattr getattr delattr 反射 后面单独讲

complex 复数

1 创建一个复数,它的值为real + imag*j;或者将一个字符串/数字转化成一个复数。如果第一个参数是个字符串,它将被解释成复数,同时函数不能有第二个参数。
2 第二个参数不能是字符串。每个参数必须是数值类型(包括复数)。如果imag被忽略,它的默认值是0,这时该函数就像是int(),long()和float()这样的数值转换函数。
3 如果两个参数都被忽略,返回0j。
4 
5 注意 当从字符串转化成复数的时候,字符串中+或者-两边不能有空白。例如,complex('1+2j')是可行的,但complex('1 + 2j')会抛出ValueError异常。
6 在Numeric Types — int, float, long, complex中有对复数的描述。

 

dir 显示类的方法

 

如果没有参数,返回当前本地作用域内的名字列表。如果有参数,尝试返回参数所指明对象的合法属性的列表。

如果对象有__dir__()方法,该方法被调用且必须返回一个属性列表。这允许实现了定制化的__getattr__()或者__getattribute__()函数的对象定制dir()报告对象属性的方式。

如果对象没有提供__dir__(),同时如果对象有定义__dict__属性,dir()会先尝试从__dict__属性中收集信息,然后是对象的类型对象。结果列表没有必要是完整的,如果对象有定制化的__getattr__(),结果还有可能是不准确的。

对于不同类型的对象,默认的dir()行为也不同,因为它尝试产生相关的而不是完整的信息:

  • 如果对象是模块对象,列表包含模块的属性名。
  • 如果对象是类型或者类对象,列表包含类的属性名,及它的基类的属性名。
  • 否则,列表包含对象的属性名,它的类的属性名和类的基类的属性名。

divmod(10,3) 显示商和余数

分页 :余数大于0 商+1 为页数

在长整数除法中,传入两个数字(非复数)作为参数,返回商和余数的二元组。
对于混合的操作数类型,应用二元算术运算符的规则。对于普通整数或者长整数,结果等同于(a // b, a % b)。对于浮点数结果是(q, a % b),q一般是math.floor(a / b),但也可能比那小1。
不管怎样,q * b + a % b非常接近于a,如果a % b非0,它和b符号相同且0 <= abs(a % b) < abs(b)。

enumerate 序列

enumerate(sequence, start=0)

返回一个枚举对象。sequence必须是个序列,迭代器iterator,或者支持迭代的对象。enumerate()返回的迭代器的next()方法返回一个元组,它包含一个计数(从start开始,默认为0)和从sequence中迭代得到的值:

1 >>> seasons = ['Spring', 'Summer', 'Fall', 'Winter']
2 >>> list(enumerate(seasons))
3 [(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
4 >>> list(enumerate(seasons, start=1))
5 [(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]

等同于:

def enumerate(sequence, start=0):
    n = start
    for elem in sequence:
        yield n, elem
        n += 1

eval # 字符串 转算 执行表达式 有返回值

eval(expression[, globals[, locals]])

参数是Unicode或者Latin-1编码的字符串,全局变量和局部变量可选。如果有全局变量,globals必须是个字典。如果有局部变量,locals可以是任何映射类型对象。

改变于版本2.4:在此之前locals需要是个字典。

expression参数被当作Python表达式来解析并演算(技术上来说,是个条件列表),使用globals和locals字典作为全局和局部的命名空间。如果globals字典存在,且缺少‘__builtins__’,在expression被解析之前,当前的全局变量被拷贝进globals。这意味着一般来说expression能完全访问标准__builtin__模块,且受限的环境会传播。如果locals字典被忽略,默认是globals字典。如果都被忽略,表达式在eval()被调用的环境中执行。返回值是被演算的表达式的结果。语法错误报告成异常。例子:

1 >>> x = 1
2 >>> print eval('x+1')
3 2
4 a = "1 + 3"
5 n = eval(a)
6 print(n)
7 ret = eval("a+60", {"a": 88})
8 print(ret)

该函数也能执行任意的代码对象(如compile()返回的结果)。 在这种情况下,传递代码对象而不是字符串。如果代码对象编译时mode参数为'exec'eval()返回None

提示:exec语句支持动态的语句执行。execfile()函数支持执行文件中的语句。globals()locals()函数返回当前的全局变量和局部变量的字典,可以传递给eval()或者execfile()

参见ast.literal_eval(),该函数能安全演算只含字面量的表达式的字符串。

exec 将字符串 执行 complie 编译功能 结合是 模板引擎

exec()没有返回值,只是执行一段Python代码

exec("for i in range(3):print(i)")

filter map reduce # filter(函数,可迭代的对象)

filter(函数,可迭代的对象)过滤,接收两个参数,一个是函数,一个是可迭代的对象,迭代每一次都执行这个函数,一旦返回True,把元素放到返回值中,迭代的对象。只有循环的时候能够直接打印出来

1 def f1(x):
2     if x >22:
3         return True
4     else:
5         return False
6 ret = filter(f1,[11,22,33])
7 # 默认处理结果返回是一个类,需要迭代打印,因为浪费内存。 可以用next迭代取值。 或者for循环 循环依次取出
8 print(next(ret))
9   print(list(ret))

 1 #filter 实现
 2 def myfilter(fuc,seq):
 3     new_li = []
 4     for i in seq:
 5         #print(i)
 6         ret = fuc(i)
 7         if ret:
 8             new_li.append(i)
 9     return new_li
10 def f1(x):
11     if x > 22:
12         return True
13     else:
14         return False
15 li = [11,22,33,44]
16 new=myfilter(f1,li)
17 print(new)

filter(function, iterable)

构造一个列表,列表的元素来自于iterable,对于这些元素function返回真。iterable可以是个序列,支持迭代的容器,或者一个迭代器。如果iterable是个字符串或者元组,则结果也是字符串或者元组;否则结果总是列表。如果function是None,使用特性函数,即为假的iterable被移除。

1 注意,在function不为None的情况下,
2   filter(function, iterable)  
3     等同于
4     [item for item in iterable if function(item)];
5     否则等同于
6     [item foritem in iterable if item](function为None)。

filter中 lambda 函数替换 函数f1

1 ret1 = filter(lambda x:x>22,[11,22,33,44])
2 print(list(ret1))
map map(函数,可迭代的对象)需要迭代打印

 1 # map 实现
 2 def mymap(fuc,seq):
 3     n_li = []
 4     for i in seq:
 5         n_i=fuc(i)
 6         n_li.append(n_i)
 7     # print(n_li)
 8     return n_li
 9 def f2(x):
10     return x+10
11 li = [11,22,33,44]
12 
13 ret = mymap(f2,li)
14 print(ret)
# map(函数,可迭代的对象),批量的操作
def fun2(x):
    return x + 100
 1 def f1(x):
 2     if x >22:
 3         return True
 4     else:
 5         return False
 6 ret1 = map(f1,[11,22,33,44])
 7 print(list(ret1))
 8 结果是:[False, False, True, True]
 9 
10 ret1 = map(lambda x:x+22,[11,22,33,44])
11 print(list(ret1))
12 结果是:[33, 44, 55, 66]
 

reduce()函数也是Python内置的一个高阶函数。

reduce()函数接收的参数和 map()类似,一个函数 f,一个list,但行为和 map()不同,reduce()传入的函数 f 必须接收两个参数,reduce()对list的每个元素反复调用函数f,并返回最终结果值。

例如,编写一个f函数,接收x和y,返回x和y的和:

1
2
def f(x, y):
    return + y

调用 reduce(f, [1, 3, 5, 7, 9])时,reduce函数将做如下计算:

1
2
3
4
5
先计算头两个元素:f(13),结果为4
再把结果和第3个元素计算:f(45),结果为9
再把结果和第4个元素计算:f(97),结果为16
再把结果和第5个元素计算:f(169),结果为25
由于没有更多的元素了,计算结束,返回结果25

上述计算实际上是对 list 的所有元素求和。虽然Python内置了求和函数sum(),但是,利用reduce()求和也很简单。

reduce()还可以接收第3个可选参数,作为计算的初始值。如果把初始值设为100,计算:

1
reduce(f, [13579], 100)

结果将变为125,因为第一轮计算是:

计算初始值和第一个元素:f(100, 1),结果为101

 
 
format 格式化 字符串拼接+ 性能低,后面讲
globals() 获取所有的全局变量
local() 获取所有局部变量
hash(对象) 获取对象hash 内存优化
返回对象的hash(哈希/散列)值(如果有的话)。hash值是整数。它被用于在字典查找时快速比较字典的键。相同的数值有相同的hash(尽管它们有不同的类型,比如1和1.0)。
 
isinstance(对象,类)

判断对象是否是某个类创建的 父类的话也成立

issubclass 是否是子类 后面讲

 

iter 迭代器 后面讲

obj = iter([11,22,33,44])
ret = next(obj)
print(ret)

yield 生成器,后面讲

max 最大 min

li = [11,22,33,44]
max(li)

pow求次方

a= pow(2,10)
print(a)

repr() === ascii()

round 四舍五入

round()方法返回 x 的小数点四舍五入到n个数字


1
语法 2 以下是round()方法的语法: 3 4 round( x [, n] ) 5 参数 6 x --这是一个数值表达式 7 8 n --这也是一个数值表达式 9 10 返回值 11 该方法返回 x 的小数点四舍五入到n个数字 12 13 例子 14 下面的例子显示了round()方法的使用 15 16 #!/usr/bin/python 17 18 print "round(80.23456, 2) : ", round(80.23456, 2) 19 print "round(100.000056, 3) : ", round(100.000056, 3) 20 print "round(-100.000056, 3) : ", round(-100.000056, 3) 21 当我们运行上面的程序,它会产生以下结果: 22 23 round(80.23456, 2) : 80.23 24 round(100.000056, 3) : 100.0 25 round(-100.000056, 3) : -100.0

slice 对象切片
在python中,list, tuple以及字符串等可以遍历访问的类型都可以应用slice访问。slice本身的意思是指切片,在这些可以遍历访问的类型中截取其中的某些部分。

sum 求和

sum(iterable[, start])

将start以及iterable的元素从左向右相加并返回总和。start默认为0iterable的元素通常是数字,start值不允许是一个字符串。

对于某些使用场景,有比sum()更好的选择。连接字符串序列的首选和快速的方式是调用''.join(sequence)如要相加扩展精度的浮点数,请参阅math.fsum()若要连接一系列的可迭代量,可以考虑使用itertools.chain()

其实sum()的参数是一个list
例如:
sum([1,2,3])
sum(range(1,11))
还有一个比较有意思的用法
a = range(1,11)
b = range(1,10)
c =  sum([item for item in a if item in b])
print c
输出:

supper 找到父类
super

(

type[, object-or-type])

返回一个代理对象,这个对象指派方法给一个父类或者同类. 这对进入类中被覆盖的继承方法非常有用。搜索顺序和 getattr() 一样。而它自己的 类型则被忽略

vars 对象的变量个数

zip 拉链 将两个列表合起来,做成一个列表,元素为数组

 1 >>> a = range(5,10)
 2 >>> a
 3 [5, 6, 7, 8, 9]
 4 >>> b =(1,5)
 5 >>> b
 6 (1, 5)
 7 >>> b =range(1,5)
 8 >>> b
 9 [1, 2, 3, 4]
10 >>> b.append(0)
11 >>> b
12 [1, 2, 3, 4, 0]
13 >>> zip(a,b)
14 [(5, 1), (6, 2), (7, 3), (8, 4), (9, 0)]
15 >>> b.pop()
16 >>> b
17 [1, 2, 3, 4]
18 >>> a
19 [5, 6, 7, 8, 9]
20 >>> zip(a,b)
21 [(5, 1), (6, 2), (7, 3), (8, 4)]

sort 函数

sorted(iterable[, cmp[, key[, reverse]]])


依据iterable中的元素返回一个新的列表。

可选参数cmp、key和reverse与list.sort()方法的参数含义相同(在可变的序列类型一节描述)。

cmp指定一个自定义的带有两个参数的比较函数(可迭代的元素),它应该根据第一个参数是小于、等于还是大于第二个参数返回负数、零或者正数:cmp=lambda x,y: cmp(x.lower(), y.lower())默认值是None

key指定一个带有一个参数的函数,它用于从每个列表元素选择一个比较的关键字:key=str.lower默认值是None(直接比较元素)。

reverse是一个布尔值。如果设置为True,那么列表元素以反向比较排序。

通常情况下,key和reverse转换处理比指定一个等同的cmp函数要快得多。这是因为cmp为每个元素调用多次但是key和reverse只会触摸每个元素一次。使用functools.cmp_to_key()来转换旧式的cmp函数为key函数。

关于排序的实例和排序的简明教程,请参阅Sorting HowTo

 1 >>> sorted([5, 2, 3, 1, 4])
 2 [1, 2, 3, 4, 5]
 3 
 4 >>> a = [5, 2, 3, 1, 4]
 5 >>> a.sort()
 6 >>> a
 7 [1, 2, 3, 4, 5]
 8 
 9 sorted 默认值对列表排序故字典只对key排序
10 >>> sorted({1: 'D', 2: 'B', 3: 'B', 4: 'E', 5: 'A'})
11 [1, 2, 3, 4, 5]
12 
13 key 函数
14 >>> sorted("This is a test string from Andrew".split(), key=str.lower)
15 ['a', 'Andrew', 'from', 'is', 'string', 'test', 'This']
16 
17 lambda
18 >>> student_tuples = [
19         ('john', 'A', 15),
20         ('jane', 'B', 12),
21         ('dave', 'B', 10),
22 ]
23 >>> sorted(student_tuples, key=lambda student: student[2])   # sort by age
24 [('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]
25 
26 The same technique works for objects with named attributes. For example:
27 
28 >>> class Student:
29         def __init__(self, name, grade, age):
30                 self.name = name
31                 self.grade = grade
32                 self.age = age
33         def __repr__(self):
34                 return repr((self.name, self.grade, self.age))
35         def weighted_grade(self):
36                 return 'CBA'.index(self.grade) / float(self.age)
37 
38 >>> student_objects = [
39         Student('john', 'A', 15),
40         Student('jane', 'B', 12),
41         Student('dave', 'B', 10),
42 ]
43 >>> sorted(student_objects, key=lambda student: student.age)   # sort by age
44 [('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]
45 
46 更多详见 https://wiki.python.org/moin/HowTo/Sorting/

 

重点掌握的

3、open() 函数 处理文件

open函数,该函数用于文件处理

操作文件时,一般需要经历如下步骤:

  • 打开文件
  • 操作文件
  • 关闭文件

而实际工作操作的时候忘了关闭文件,所以我们用另一种操作,用with语句来操作,这样就不需要手动来关闭文件。在后面的操作中,都会以with方式来打开文件。

一、打开文件

文件句柄 = open('文件路径', '模式')

打开文件时,需要指定文件路径和以何等方式打开文件,打开后,即可获取该文件句柄,日后通过此文件句柄对该文件操作。
 1 #windows下默认为gbk,要指定编码为'utf-8'
 2 #'r'为只读,'1.txt'为文件路径
 3 f=open('1.txt','r',encoding='utf-8')  #打开文件
 4 data=f.read()               #操作文件
 5 f.close()                 #关闭文件
 6 print(data)
 7  
 8 # 用with语句打开,不需要自动关闭
 9 with open('1.txt','r',encoding='utf-8') as f:
10     print(f.read())

打开文件的模式有:

  • r ,只读模式【默认】
  • w,只写模式【不可读;不存在则创建;存在则清空内容;】
  • x, 只写模式【不可读;不存在则创建,存在则报错】
  • a, 追加模式【不可读; 不存在则创建;存在则只追加内容;】

"+" 表示可以同时读写某个文件

  • r+, 读写【可读,可写】
  • w+,写读【可读,可写】
  • x+ ,写读【可读,可写】
  • a+, 写读【可读,可写】

 "b"表示以字节的方式操作

  • rb  或 r+b 
  • wb 或 w+b
  • xb 或 w+b
  • ab 或 a+b

 注:以b方式打开时,读取到的内容是字节类型,写入时也需要提供字节类型

 

 1 文件 hello.txt
 2 Hello Word!
 3 abc
 4 abc
 5 abc
 6 汉字 7 
 8 代码 :
 9 f = open("hello.txt",'rb') # 用到b模式的时候 就不能跟 编码了。
10 data = f.read()
11 f.close()
12 print(data)
13 
14 输出
15 C:\Python35\python3.exe E:/py_test/s5/open.py
16 b'Hello Word!\r\n123\r\nabc\r\n456\r\nabc\r\n789\r\nabc\r\n\xe5\x88\x98\xe5\xbb\xba\xe4\xbd\x90'

python open函数 r 和rb区别

 

 

下面着重讲解下用"+" 同时读写某个文件的操作

 1 # r+形式 写的时候,如果直接写,在写之前没有读取过就是直接从前面开始写进去,tell指针位置是你写之后的位置,再次读取也是从这个位置开始读,如果有读过,不管事read 还是readline 还是read(1)都是在末尾追加,指针移到到最后。
但是读的话还是从之前读之后的tell位置继续读。
 2 # 大家一定要清楚的明白读写的时候指针指向的位置,下面的这个例子一定要懂
 3 # f.tell()   读取指针的位置
 4 # f.seek(0)  设置指针的位置
 5 with open('1.txt','r+',encoding='utf-8') as f:
 6     print(f.tell())            #打印下 文件开始时候指针指向哪里 这里指向 0
 7     print(f.read())            #读出文件内容'字符串',读了几个指针到什么位置,read是全部读完了。
 8     print(f.tell())            #文件指针位置,读了几个位置,就在哪个位置,如果read()了,那就在最后,如果read(1) tell 就是1
 9     f.write('科比')            #写入内容'科比',需要特别注意,如果没有读全部,或者没有读过,直接写入的话是从指针为0的位置开始写入,原先有内容的话会覆盖原来的内容,如果读取过,那么不管指针在哪都是追加到最后的。并且指针tell也在最后
10     print(f.read())            #写完之后再次去读的时候,需要特别注意的是,读的位置,是你之前读之后的位置,而不是写完之后tell的位置
11     print(f.tell())            #指针指到15
12     f.seek(0)                  #将指针内容指到 0 位置,移动指针的时候,要注意汉字连续字节不能被拆分开,不然报错,
13 print(f.read()) #因为文件指针指到开头去了,所以可以读到内容 字符串科比 14 15 # w+形式 存在的话先清空 一写的时候指针到最后 16 with open('1.txt','w+') as f: 17 f.write('Kg') #1.txt存在,所以将内面的内容清空,然后再写入 'kg' 18 print(f.tell()) #此时指针指向2 19 print(f.read()) #读不到内容,因为指针指向末尾了 20 f.seek(0) 21 print(f.read()) #读到内容,因为指针上一步已经恢复到起始位置 22 23 # a+打开的时候指针已经移到最后,写的时候不管怎样都往文件末尾追加,这里就不再演示了,读者可以自己试一下 24 # x+文件存在的话则报错,也不演示了

Python文件读取方式

 二、操作

  1 class file(object)
  2     def close(self): # real signature unknown; restored from __doc__
  3         关闭文件
  4         """
  5         close() -> None or (perhaps) an integer.  Close the file.
  6          
  7         Sets data attribute .closed to True.  A closed file cannot be used for
  8         further I/O operations.  close() may be called more than once without
  9         error.  Some kinds of file objects (for example, opened by popen())
 10         may return an exit status upon closing.
 11         """
 12  
 13     def fileno(self): # real signature unknown; restored from __doc__
 14         文件描述符  
 15          """
 16         fileno() -> integer "file descriptor".
 17          
 18         This is needed for lower-level file interfaces, such os.read().
 19         """
 20         return 0    
 21  
 22     def flush(self): # real signature unknown; restored from __doc__
 23         刷新文件内部缓冲区,将内存中写入的内容刷进硬盘。
 24         """ flush() -> None.  Flush the internal I/O buffer. """
 25         pass
 26  
 27  
 28     def isatty(self): # real signature unknown; restored from __doc__
 29         判断文件是否是同意tty设备
 30         """ isatty() -> true or false.  True if the file is connected to a tty device. """
 31         return False
 32  
 33  
 34     def next(self): # real signature unknown; restored from __doc__
 35         获取下一行数据,不存在,则报错
 36         """ x.next() -> the next value, or raise StopIteration """
 37         pass
 38  
 39     def read(self, size=None): # real signature unknown; restored from __doc__
 40         读取指定字节数据,默认读取全部,汉字的话读取按照字符来读。
 41         """
 42         read([size]) -> read at most size bytes, returned as a string.
 43          
 44         If the size argument is negative or omitted, read until EOF is reached.
 45         Notice that when in non-blocking mode, less data than what was requested
 46         may be returned, even if no size parameter was given.
 47         """
 48         pass
 49  
 50     def readinto(self): # real signature unknown; restored from __doc__
 51         读取到缓冲区,不要用,将被遗弃
 52         """ readinto() -> Undocumented.  Don't use this; it may go away. """
 53         pass
 54  
 55     def readline(self, size=None): # real signature unknown; restored from __doc__
 56         仅读取一行数据
 57         """
 58         readline([size]) -> next line from the file, as a string.
 59          
 60         Retain newline.  A non-negative size argument limits the maximum
 61         number of bytes to return (an incomplete line may be returned then).
 62         Return an empty string at EOF.
 63         """
 64         pass
 65  
 66     def readlines(self, size=None): # real signature unknown; restored from __doc__
 67         读取所有数据,并根据换行保存值列表
 68         """
 69         readlines([size]) -> list of strings, each a line from the file.
 70          
 71         Call readline() repeatedly and return a list of the lines so read.
 72         The optional size argument, if given, is an approximate bound on the
 73         total number of bytes in the lines returned.
 74         """
 75         return []
 76  
 77     def seek(self, offset, whence=None): # real signature unknown; restored from __doc__
 78         指定文件中指针位置
 79         """
 80         seek(offset[, whence]) -> None.  Move to new file position.
 81          
 82         Argument offset is a byte count.  Optional argument whence defaults to
 83 (offset from start of file, offset should be >= 0); other values are 1
 84         (move relative to current position, positive or negative), and 2 (move
 85         relative to end of file, usually negative, although many platforms allow
 86         seeking beyond the end of a file).  If the file is opened in text mode,
 87         only offsets returned by tell() are legal.  Use of other offsets causes
 88         undefined behavior.
 89         Note that not all file objects are seekable.
 90         """
 91         pass
 92  
 93     def tell(self): # real signature unknown; restored from __doc__
 94         获取当前指针位置
 95         """ tell() -> current file position, an integer (may be a long integer). """
 96         pass
 97  
 98     def truncate(self, size=None): # real signature unknown; restored from __doc__
 99         截断数据,仅保留指定之前数据,指针所在位置之前的内容
100         """
101         truncate([size]) -> None.  Truncate the file to at most size bytes.
102          
103         Size defaults to the current file position, as returned by tell().
104         """
105         pass
106  
107     def write(self, p_str): # real signature unknown; restored from __doc__
108         写内容
109         """
110         write(str) -> None.  Write string str to file.
111          
112         Note that due to buffering, flush() or close() may be needed before
113         the file on disk reflects the data written.
114         """
115         pass
116  
117     def writelines(self, sequence_of_strings): # real signature unknown; restored from __doc__
118         将一个字符串列表写入文件
119         """
120         writelines(sequence_of_strings) -> None.  Write the strings to the file.
121          
122         Note that newlines are not added.  The sequence can be any iterable object
123         producing strings. This is equivalent to calling write() for each string.
124         """
125         pass
126  
127     def xreadlines(self): # real signature unknown; restored from __doc__
128         可用于逐行读取文件,非全部
129         """
130         xreadlines() -> returns self.
131          
132         For backward compatibility. File objects now include the performance
133         optimizations previously implemented in the xreadlines module.
134         """
135         pass
136 
137 2.x
138 
139 2.x Code
View Code

 

  1 class TextIOWrapper(_TextIOBase):
  2     """
  3     Character and line based layer over a BufferedIOBase object, buffer.
  4     
  5     encoding gives the name of the encoding that the stream will be
  6     decoded or encoded with. It defaults to locale.getpreferredencoding(False).
  7     
  8     errors determines the strictness of encoding and decoding (see
  9     help(codecs.Codec) or the documentation for codecs.register) and
 10     defaults to "strict".
 11     
 12     newline controls how line endings are handled. It can be None, '',
 13     '\n', '\r', and '\r\n'.  It works as follows:
 14     
 15     * On input, if newline is None, universal newlines mode is
 16       enabled. Lines in the input can end in '\n', '\r', or '\r\n', and
 17       these are translated into '\n' before being returned to the
 18       caller. If it is '', universal newline mode is enabled, but line
 19       endings are returned to the caller untranslated. If it has any of
 20       the other legal values, input lines are only terminated by the given
 21       string, and the line ending is returned to the caller untranslated.
 22     
 23     * On output, if newline is None, any '\n' characters written are
 24       translated to the system default line separator, os.linesep. If
 25       newline is '' or '\n', no translation takes place. If newline is any
 26       of the other legal values, any '\n' characters written are translated
 27       to the given string.
 28     
 29     If line_buffering is True, a call to flush is implied when a call to
 30     write contains a newline character.
 31     """
 32     def close(self, *args, **kwargs): # real signature unknown
 33         关闭文件
 34         pass
 35 
 36     def fileno(self, *args, **kwargs): # real signature unknown
 37         文件描述符  
 38         pass
 39 
 40     def flush(self, *args, **kwargs): # real signature unknown
 41         刷新文件内部缓冲区
 42         pass
 43 
 44     def isatty(self, *args, **kwargs): # real signature unknown
 45         判断文件是否是同意tty设备
 46         pass
 47 
 48     def read(self, *args, **kwargs): # real signature unknown
 49         读取指定字节数据
 50         pass
 51 
 52     def readable(self, *args, **kwargs): # real signature unknown
 53         是否可读
 54         pass
 55 
 56     def readline(self, *args, **kwargs): # real signature unknown
 57         仅读取一行数据
 58         pass
 59 
 60     def seek(self, *args, **kwargs): # real signature unknown
 61         指定文件中指针位置
 62         pass
 63 
 64     def seekable(self, *args, **kwargs): # real signature unknown
 65         指针是否可操作
 66         pass
 67 
 68     def tell(self, *args, **kwargs): # real signature unknown
 69         获取指针位置
 70         pass
 71 
 72     def truncate(self, *args, **kwargs): # real signature unknown
 73         截断数据,仅保留指定之前数据
 74         pass
 75 
 76     def writable(self, *args, **kwargs): # real signature unknown
 77         是否可写
 78         pass
 79 
 80     def write(self, *args, **kwargs): # real signature unknown
 81         写内容
 82         pass
 83 
 84     def __getstate__(self, *args, **kwargs): # real signature unknown
 85         pass
 86 
 87     def __init__(self, *args, **kwargs): # real signature unknown
 88         pass
 89 
 90     @staticmethod # known case of __new__
 91     def __new__(*args, **kwargs): # real signature unknown
 92         """ Create and return a new object.  See help(type) for accurate signature. """
 93         pass
 94 
 95     def __next__(self, *args, **kwargs): # real signature unknown
 96         """ Implement next(self). """
 97         pass
 98 
 99     def __repr__(self, *args, **kwargs): # real signature unknown
100         """ Return repr(self). """
101         pass
102 
103     buffer = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
104 
105     closed = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
106 
107     encoding = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
108 
109     errors = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
110 
111     line_buffering = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
112 
113     name = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
114 
115     newlines = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
116 
117     _CHUNK_SIZE = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
118 
119     _finalizing = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
120 
121 3.x
122 
123 3.x
3.0

 

操作示例:

测试的文件名是 "hello.txt" ,文件内容为:

1 Hello Word!
2 abc
3 abc
4 abc

 

read 方法

 1 # 以只读的方式打开文件hello.txt
 2 f = open("hello.txt","r")
 3 # 读取文件内容赋值给变量c
 4 c = f.read()
 5 # 关闭文件
 6 f.close()
 7 # 输出c的值
 8 print(c)
 9 
10 输出结果
11 C:\Python35\python3.exe E:/py_test/s5/open.py
12 Hello Word!
13 abc
14 abc
15 abc

 

readline

 1 # 以只读模式打开文件hello.txt
 2 f = open("hello.txt","r")
 3 # 读取第一行  strip 去除空行
 4 c1 = f.readline().strip()
 5 # 读取第二行 
 6 c2 = f.readline().strip()
 7 # 读取第三行
 8 c3 = f.readline().strip()
 9 # 关闭文件
10 f.close()
11 # 输出读取文件第一行内容
12 print(c1)
13 # 输出读取文件第二行内容
14 print(c2)
15 # 输出读取文件第三行内容
16 print(c3)
17 
18 C:\Python35\python.exe F:/Python_code/sublime/Day06/file.py
19 Hello Word!
20 123
21 abc

 

readlines 获取到的是列表,每行是列表的元素

 1 # 以只读的方式打开文件hello.txt
 2 f = open("hello.txt","r")
 3 # 将文件所有内容赋值给c
 4 c = f.readlines()
 5 # 查看数据类型
 6 print(type(c))
 7 # 关闭文件
 8 f.close()
 9 # 遍历输出文件内容 # n.strip()去除空行
10 for n in c:
11     print(n.strip())
12 
13 C:\Python35\python3.exe E:/py/55/learn-python/oldboy/4/test_file.py
14 <class 'list'>
15 Hello Word!
16 abc
17 abc
18 abc

 

Python文件写入方式

 

write

1 # 以只写的模式打开文件write.txt,没有则创建,有则覆盖内容
2 file = open("write.txt","w")
3 # 在文件内容中写入字符串test write
4 file.write("test write")
5 # 关闭文件
6 file.close()

 

writeline

# 以只写模式打开一个不存在的文件wr_lines.txt
f = open("wr_lines.txt","w",encoding="utf-8")
# 写入一个列表
f.writelines(["11","22","33"])
# 关闭文件
f.close()

wr_lines.txt 文件内容:

 

Python文件操作所提供的方法

 

close(self):
  关闭已经打开的文件

 

f.close()

 

fileno(self):
  文件描述符

1 f = open("hello.txt",'rb')
2 data = f.fileno()
3 f.close()
4 print(data)

输出结果

C:\Python35\python3.exe E:/py_test/s5/open.py
  3

 

flush(self):

刷新缓冲区的内容到硬盘中

f.flush() #在r+ 或者 rb+模式下还没有 f.close() 或者之后,flush方法 就会将内存的数据写入硬盘。 否则在其他地方调用这个文件的新内容会找不到

 

isatty(self):
  判断文件是否是tty设备,如果是tty设备则返回 True ,否则返回 False

f = open("hello.txt","r")
ret = f.isatty()
f.close()
print(ret)

C:\Python35\python.exe F:/Python_code/sublime/Day06/file.py
False

 

readable(self):
  是否可读,如果可读返回 True ,否则返回 False

1 f = open("hello.txt","r")
2 ret = f.readable()
3 f.close()
4 print(ret)
5 
6 C:\Python35\python.exe F:/Python_code/sublime/Day06/file.py
7 True

 

readline(self, limit=­1):
  每次仅读取一行数据

f = open("hello.txt","r")
print(f.readline())
print(f.readline())
f.close()

C:\Python35\python.exe F:/Python_code/sublime/Day06/file.py
Hello Word!
123

 

readlines(self, hint=­1):
  把每一行内容当作列表中的一个元素

f = open("hello.txt","r")
print(f.readlines())
f.close()

C:\Python35\python.exe F:/Python_code/sublime/Day06/file.py
['Hello Word!\n', '123\n', 'abc\n', '456\n', 'abc\n', '789\n', 'ab
c']

 

tell(self):
  获取指针位置

1 f = open("hello.txt","r")
2 print(f.tell())
3 f.close()
4 
5 C:\Python35\python.exe F:/Python_code/sublime/Day06/file.py
6 0

 

seek(self, offset, whence=io.SEEK_SET):
  指定文件中指针位置

f = open("hello.txt","r")
print(f.tell())
f.seek(3)
print(f.tell())
f.close()

C:\Python35\python.exe F:/Python_code/sublime/Day06/file.py
0 3

 

seekable(self):
  指针是否可操作

1 f = open("hello.txt","r")
2 print(f.seekable())
3 f.close()
4 
5 C:\Python35\python.exe F:/Python_code/sublime/Day06/file.py
6 True

 

writable(self):
  是否可写

1 f = open("hello.txt","r")
2 print(f.writable()) #只读模式不可读
3 f.close()
4 
5 C:\Python35\python.exe F:/Python_code/sublime/Day06/file.py
6 False

 

writelines(self, lines):
  写入文件的字符串序列,序列可以是任何迭代的对象字符串生产,通常是一个 字符串列表 。

1 f = open("wr_lines.txt","w")
2 f.writelines(["11","22","33"])
3 f.close()
4 
5 写入结果
6 112233

 

read(self, n=None):
  读取指定字节数据,后面不加参数默认读取全部

f = open("wr_lines.txt","r")
print(f.read(3))
f.seek(0)
print(f.read())
f.close()

C:\Python35\python.exe F:/Python_code/sublime/Day06/file.py
112
112233

 

write(self, s):
  往文件里面写内容

1 f = open("wr_lines.txt","w")
2 f.write("abcabcabc")
3 f.close()
4 
5 文件内容
6 abcabcabc

 

 

 

 一行一行的读文件 for in

f=open("test.txt","r")

for line in f:

  print(line) #一行一行将文件读出来

 

假设现在有这样一个需求,有一个10G大的文件,如何拷贝到另一个文件中去?下面将讲一下如何同时打开两个文件进行处理,以及文件太大的时候如何读取用with语句就可以同时打开两个文件,一个读,一个写。假设1.txt文件有10G大,如果用read则一次性就将内容读到内存中去了,这显然不合适,如果用readline()的话虽然也可以读一行,但是并不知道何时结束,但是可以用for循环读取文件这个可迭代的对象,一行行的读取。下面三行代码就可以实现了

 

1 with open('1.txt','r',encoding='utf-8') as fread,open('2.txt','w') as fwrite:
2     for line in fread:          #一行行的读
3         fwrite.write(line)        #一行行的写

三、管理上下文

为了避免打开文件后忘记关闭,可以通过管理上下文,即:

with open('log','r') as f:
        
    ...

如此方式,当with代码块执行完毕时,内部会自动关闭并释放文件资源。

在Python 2.7 及以后,with又支持同时对多个文件的上下文进行管理,即:

 

with open('log1') as obj1, open('log2') as obj2:
    pass

 

 open fileinput 练习 更改文本内容 增删改查用户 以及注册登陆

 

  1 #!/usr/bin/env python
  2 # -*- coding:utf-8 -*-
  3 def login(username, password):
  4     """
  5     判断用户名,密码是否正确
  6     :param username: 用户名
  7     :param password: 密码
  8     :return: True:正确登陆,False:用户名或密码错误,无法登陆
  9     """
 10     with open("db", "r", encoding="utf-8") as f:
 11         for line in f:
 12             line_list = line.strip().split(":")
 13             if username == line_list[0] and password == line_list[1]:
 14                 return True
 15     return False
 16 
 17 def register():
 18     """
 19     新用户注册判断用户名是否存在,密码位数是否正确
 20     :return: True:注册成功
 21     """
 22     user = input("请输入用户名:")
 23     while True:
 24         ret = user_exist(user)  # 判断用户名是否存在
 25         if ret:
 26             print("用户名已存在!")
 27             user = input("请重新输入用户名:")
 28             continue
 29         else:
 30             break
 31     pwd = pwd_rule()  # 密码规则验证及获取输入密码
 32     with open("db", "a") as f:
 33         if f.tell() != 0:
 34             temp = "\n" + user + ":" + pwd
 35             f.write(temp)
 36             return True
 37         else:
 38             temp = user + ":" + pwd
 39             f.write(temp)
 40             return True
 41 
 42 def user_exist(username):
 43     '''
 44     验证密码用户名是否重复
 45     :param username: 用户名
 46     :return: True:用户名重复
 47     '''
 48     with open("db", "r", encoding="utf-8") as f:
 49         for line in f:
 50             line_list = line.strip().split(":")
 51             if username == line_list[0]:
 52                 return True
 53     return False
 54 
 55 def change_pwd(username, password):
 56     """
 57     修改密码
 58     :param username: 原始账户
 59     :param password: 原始密码
 60     :return: True:修改成功。
 61     """
 62     with open("db", "r", encoding="utf-8") as f:
 63         data = f.readlines()
 64         # print(data)
 65         for i in range(len(data)):
 66             line_list = data[i].strip().split(":")
 67             if username == line_list[0] and password == line_list[1]:  # 判定账户输入正确
 68                 print("验证成功,开始设定新密码\n")
 69                 new_pwd = pwd_rule()
 70                 print(new_pwd)
 71                 data[i] = username + ":" + new_pwd + "\n"  # 设定新密码行
 72                 with open("db", "w", encoding="utf-8") as n:
 73                     n.writelines(data)  # 重新写进去
 74                     return True
 75     print("验证失败")
 76     return False
 77 
 78 def del_user(username, password):
 79     with open("db", "r", encoding="utf-8") as f:
 80         data = f.readlines()
 81         # print(data)
 82         for i in range(len(data)):
 83             line_list = data[i].strip().split(":")
 84             if username == line_list[0] and password == line_list[1]:  # 判定账户输入正确
 85                 print("验证成功,确定删除用户\n")
 86                 inp = input("y/s?")
 87                 if inp == "y":
 88                     del data[i]
 89                     with open("db", "w", encoding="utf-8") as n:
 90                         n.writelines(data)  # 重新写进去
 91                         print("删除成功")
 92                         return True
 93                 else:
 94                     print("取消删除")
 95                     return True
 96 
 97     print("验证失败")
 98     return False
 99 
100 def pwd_rule():
101     """
102     新密码的输入,判定密码规则是否符合
103     :return: 返回密码
104     """
105     while True:
106         password = input("请输入密码:")
107         if len(password) < 6:  # 密码少于6位需要重新输入
108             print("密码至少6位")
109             # password = input("重新输入密码:")
110             continue
111         pwd_again = input("请再次输入:")  # 密码2次确认。2次输入错误重新输入。
112         if password == pwd_again:
113             return password
114         else:
115             print("两次输入不一样")
116             continue
117 
118 def confirm(chose):
119     """
120     操作选项
121     :param chose: 选项
122     :return: 无
123     """
124     while True:
125         if chose == 1:
126             flag = False
127             while True:
128                 user = input("请输入用户名:")
129                 pwd = input("请输入密码:")
130                 ret = login(user, pwd)
131                 if ret:
132                     print("登陆成功")
133                     flag = True
134                     break
135                 else:
136                     print("登陆失败,重新登陆")
137                     continue
138             if flag:
139                 break
140         elif chose == 2:
141             ret = register()
142             if ret:
143                 print("注册成功")
144                 break
145 
146         elif chose == 3:
147             user = input("请输入用户名:")
148             pwd = input("请输入密码:")
149             if change_pwd(user, pwd):
150                 print("密码修改成功")
151                 break
152         elif chose == 4:
153             user = input("请输入用户名:")
154             pwd = input("请输入密码:")
155             if del_user(user, pwd):
156                 print("操作完成")
157                 break
158         elif chose == 5:
159             print("退出")
160             break
161         else:
162             new_chose = int(input("输入错误,重新选择:\n"))
163             chose = new_chose
164             continue
165 
166 def main():
167     print("欢迎登陆SB系统!")
168     print("请选择:\n1、登陆\n2、注册\n3、修改密码\n4、删除用户\n5、退出")
169     inp = int(input())
170     confirm(inp)
171 
172 if __name__ == "__main__":
173     main()

 

posted @ 2017-02-23 18:50  崔崔0624  阅读(3075)  评论(0编辑  收藏  举报
TOP