首页 技术 正文
技术 2022年11月18日
0 收藏 480 点赞 3,138 浏览 27968 个字

上节重点回顾:

  判断对象是否属于某个类,例如:

  列表中有个数字,但是循环列表判断长度,用len会报错;因为int不支持len,所以要先判断属于某个类,然后再进行if判断。

# isinstance(对象,类名) 判断变量输入的对象是否是属于这个类
# 方法1:
temp = [11, 22, "", " ", []]
print(isinstance(temp, (str, list, tuple))) # 一旦对象属于这个后面元组的类中的任何一个 就返回true
# 方法2:
a = type(temp) is list
print(a)

判断列表长度

二、函数、参数引用

  python中函数进行传参的是是传引用,形参是指针映射到实际参数的内存地址中,一旦更改形参对应的值,实际参数也会更改。而java、c#形参和实参都生成了一份数据,这个功能完成只需要在形参处加一个ref out/再创建一份值

  python函数的形参,是有一个类似于指针的东西指向实际参数,

函数参数–引用–1:修改、删除形参的值实际参数的值也发生变化

  函数调用,而实际参数传入的是一个列表,这个就是形式参数args=实际参数 ,li= []

Python全栈之路4–内置函数–文件操作

函数–参数引用–2:对形式参数进行赋值,就是另外开辟内存空间

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

Python全栈之路4–内置函数–文件操作

赋值    尽管  函数调用的时候  args= li 但是重新赋值,等于申请了新的内存空间
def func(args):
args = 123li = [1,2,3,4]
a = func(li)
print(li)>>>[1,2,3,4]

三、lamdba匿名函数

Python全栈之路4–内置函数–文件操作

#####lamdba 匿名函数#######
def f1(arg1,arg2):
return arg1 + arg2f2 = lambda arg3,arg4 : arg3 + arg4ret = f2(3,4)
print(ret)

三元运算来表示简单的if else语句

# 普通条件语句
if 1 == 1:
name = 'wupeiqi'
else:
name = 'alex'# 三元运算
name = 'wupeiqi' if 1 == 1 else 'alex'

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

# ###################### 普通函######################
# 定义函数(普通方式)
def func(arg):
return arg + 1# 执行函数
result = func(123)# ######################lambda######################
# 定义函数(lambda表达式)
my_lambda = lambda arg : arg + 1# 执行函数
result = my_lambda(123)

四、python的内置函数

Python全栈之路4–内置函数–文件操作

更详细的官方资料:就在这里(你点啊)

大部分加单的函数

4.1、abs() 返回值是一个数字的绝对值,如果是复数,返回值是复数的模

print(abs(-100))>>>100
print(abs(1+2j))>>>2.23606

4.2、all() 所有的值为真时才为真,只要有一个是假就是假

  假:0、None、”、

4.3、any() 与all()相反只要有一个为真就是真

4.4、ascii() 用法:ascii(对象)  去类中找__repr__方法,并获取返回值

class Foo(object):
def __repr__(self):
return "hello repr"li = Foo()
n = ascii(li)
print(n)

4.5、bin二进制、cot八进制、int十进制、hex十六进制

# bin() 可以将 八 十 十六 进制 转换成二进制
print(bin(10), bin(0o13), bin(0x14))
# oct() 可以将 二 十 十六 进制 转换为八进制
print(oct(10), oct(0b101), oct(0x14))
# int() 可以将 二 八 十六进制转换为十进制
print(int(0o13), int(0b101), int(0x14))
# hex() 可以将 二 八 十 进制转换为十六进制
print(hex(0b101), hex(110), hex(0o12))

4.6、bool判断真假

python中除了”、””、0、()、[]、{}、None为False之外,其他的都是True。

4.7、bytes和bytearray字节列表

bytes(‘str’,encoding=’utf-8′)

bytearray([source[,encoding[,errors]]])

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

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

返回一个单字符字符串,字符ascii码为整数i,例如chr(97)返回值是字符串‘a’

打印 字母 数字
# 随机验证码 程序:
# 65 -90 A - Z
# 而 random.randrange(num1,num2) 大于等于num1 小于num2 的随机数import randomtmp = ""
for i in range(6):
num = random.randrange(0, 4) # 0-3 随机
if num == 2 or num == 3: # 随机数字时候 赋值随机数字
rad1 = random.randrange(0, 9)
rad1 = str(rad1) #转换字符串
tmp += rad1 #字符串拼接
else:
rad2 = random.randrange(65, 91)
rad2 = chr(rad2)
tmp += rad2
print("本次验证码:", tmp)

4.9、callable(object)

检查某一个对象是否可以被执行即:对象()

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

4.10、classmethod()

4.11、compile() 编译  默认读文件 都是字符串,经过编译之后成为代码

#!usr/bin/env python
#coding:utf-8namespace = {'name':'wupeiqi','data':[18,73,84]}code = '''def hellocute():return "name %s ,age %d" %(name,data[0],) '''func = compile(code, '<string>', "exec")exec func in namespaceresult = namespace['hellocute']()print result

4.12、hasattr  getattr  delaattr 反射

4.13、complex  复数

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

4.14、dir 显示类的方法

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

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

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

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

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

返回的列表按字母顺序排序。例如

>>> import struct
>>> dir() # show the names in the module namespace
['__builtins__', '__doc__', '__name__', 'struct']
>>> dir(struct) # show the names in the struct module
['Struct', '__builtins__', '__doc__', '__file__', '__name__',
'__package__', '_clearcache', 'calcsize', 'error', 'pack', 'pack_into',
'unpack', 'unpack_from']
>>> class Shape(object):
def __dir__(self):
return ['area', 'perimeter', 'location']
>>> s = Shape()
>>> dir(s)
['area', 'perimeter', 'location']

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

4.16、enumerate(sequence,start=0)

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

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

等同于:

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

4.17、eval  #字符串  转换  执行表达式  有返回值

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

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

>>> x = 1
>>> print eval('x+1')a = "1 + 3"
n = eval(a)print(n)
ret = eval("a+60", {"a": 88})
print(ret)

4.18、exec 将字符串  执行 

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

4.19 filter、map、reduce 

filter(函数, 迭代对象)

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

Python全栈之路4–内置函数–文件操作

#filter 实现
def myfilter(fuc,seq):
new_li = []
for i in seq:
#print(i)
ret = fuc(i)
if ret:
new_li.append(i)
return new_li
def f1(x):
if x > 22:
return True
else:
return False
li = [11,22,33,44]
new=myfilter(f1,li)
print(new)

filter(function, iterable)

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

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

filter中  lambda 函数 替换  函数f1

 ret1 = filter(lambda x:x>22,[11,22,33,44])
print(list(ret1))

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

Python全栈之路4–内置函数–文件操作

# map 实现
def mymap(fuc,seq):
n_li = []
for i in seq:
n_i=fuc(i)
n_li.append(n_i)
# print(n_li)
return n_li
def f2(x):
return x+10
li = [11,22,33,44]ret = mymap(f2,li)
print(ret)
def f1(x):
if x >22:
return True
else:
return False
ret1 = map(f1,[11,22,33,44])
print(list(ret1))
结果是:[False, False, True, True]ret1 = map(lambda x:x+22,[11,22,33,44])
print(list(ret1))
结果是:[33, 44, 55, 66]

4.20、format   格式化   字符串拼接 +  性能较低

4.21、globals() 获取所有的全局变量

4.22、local()  获取所有的局部变量

4.23、hash(对象) 获取对象的hash   内存优先

返回对象的hash(哈希/散列)值(如果有的话)。hash值是整数。它被用于在字典查找时快速比较字典的键。相同的数值有相同的hash(尽管它们有不同的类型,比如1和1.0)。

4.24、isinstance(对象, 类)

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

4.25、issubclass  是否是子类

4.26、iter  迭代器 

4.27、yield  生成器

4.28、max  min

4.29 pow  求次方

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

4.30 repr() === ascii()

4.31、round  四舍五入

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

语法
以下是round()方法的语法:round( x [, n] )
参数
x --这是一个数值表达式n --这也是一个数值表达式返回值
该方法返回 x 的小数点四舍五入到n个数字例子
下面的例子显示了round()方法的使用#!/usr/bin/pythonprint "round(80.23456, 2) : ", round(80.23456, 2)
print "round(100.000056, 3) : ", round(100.000056, 3)
print "round(-100.000056, 3) : ", round(-100.000056, 3)
当我们运行上面的程序,它会产生以下结果:round(80.23456, 2) : 80.23
round(100.000056, 3) : 100.0
round(-100.000056, 3) : -100.0

4.32、slice 对象切片

在python中 list、tuple以及字符串等可以遍历访问的类型都可以以slice访问

4.33、sum  求和

sum(iterable[,start])

其实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
输出:

4.34、supper  找到父类

4.35、vars 对象的变量个数

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

>>> a = range(5,10)
>>> a
[5, 6, 7, 8, 9]
>>> b =(1,5)
>>> b
(1, 5)
>>> b =range(1,5)
>>> b
[1, 2, 3, 4]
>>> b.append(0)
>>> b
[1, 2, 3, 4, 0]
>>> zip(a,b)
[(5, 1), (6, 2), (7, 3), (8, 4), (9, 0)]
>>> b.pop()>>> b
[1, 2, 3, 4]
>>> a
[5, 6, 7, 8, 9]
>>> zip(a,b)
[(5, 1), (6, 2), (7, 3), (8, 4)]

4.37、sort 函数

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

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

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

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

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

>>> sorted([5, 2, 3, 1, 4])
[1, 2, 3, 4, 5]>>> a = [5, 2, 3, 1, 4]
>>> a.sort()
>>> a
[1, 2, 3, 4, 5]sorted 默认值对列表排序故字典只对key排序
>>> sorted({1: 'D', 2: 'B', 3: 'B', 4: 'E', 5: 'A'})
[1, 2, 3, 4, 5]key 函数
>>> sorted("This is a test string from Andrew".split(), key=str.lower)
['a', 'Andrew', 'from', 'is', 'string', 'test', 'This']lambda
>>> student_tuples = [
('john', 'A', 15),
('jane', 'B', 12),
('dave', 'B', 10),
]
>>> sorted(student_tuples, key=lambda student: student[2]) # sort by age
[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]The same technique works for objects with named attributes. For example:>>> class Student:
def __init__(self, name, grade, age):
self.name = name
self.grade = grade
self.age = age
def __repr__(self):
return repr((self.name, self.grade, self.age))
def weighted_grade(self):
return 'CBA'.index(self.grade) / float(self.age)>>> student_objects = [
Student('john', 'A', 15),
Student('jane', 'B', 12),
Student('dave', 'B', 10),
]
>>> sorted(student_objects, key=lambda student: student.age) # sort by age
[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]更多详见 https://wiki.python.org/moin/HowTo/Sorting/

五、open()   函数  文件处理

open() 函数、该函数用于文件的处理操作步骤:

  • 打开文件
  • 操作文件

5.1、打开文件

文件句柄 = open('文件路径', '打开方式')

打开文件时,需要指定文件路径和打开方式,打开后,即可获得文件句柄,此后通过句柄进行文件操作

文件句柄 = open('文件路径','打开模式')    文件句柄相当于于变量名,文件路径可以写为绝对路径也可以写为相对路径。文件句柄可以循环 每次1行
for line in 文件句柄:
  文件句柄.write("新文件")

打开文件的模式有:

  • r ,只读模式【默认】
  • w,只写模式【不可读;不存在则创建;存在则清空内容;】
  • x, 只写模式【不可读;不存在则创建,存在则报错】
  • a, 追加模式【不可读; 不存在则创建;存在则只追加内容;】
with open('1.txt','r',encoding='utf-8') as f:
print(f.read())         # 1.txt,不存在,报错 # # w只写(不可读,不存在创建,存在则清空)
with open('1.txt','w') as f:
f.write('888')         #创建1.txt 写入新内容888 #x 只写(不可读,不存在创建,存在报错)
with open('1.txt','x') as f:
f.write('666')        #这里存在,报错 # a 追加模式(不可读,不存在创建,存在往末尾追加)
with open('1.txt','a') as f:
f.write('777')        #往1.txt里面追加 777 #以字节方式打开
#将1.txt里面的文件内容清空,往里面写入‘字符串’
#需要自己手动转换
with open('1.txt','wb') as f:
str_data='字符串'
byte_data=bytes(str_data,encoding='utf-8')
f.write(byte_data)
#以rb读
with open('1.txt','rb') as f:
data=f.read()
print(type(data))               #打印出读取的类型 字节
str_data=str(data,encoding='utf-8')     #字节转换成字符串
print(str_data)   #打印出'字符串'

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

  • r+, 读写【可读,可写】
  • w+,写读【可读,可写】
  • x+ ,写读【可读,可写】
  • a+, 写读【可读,可写】
# r+形式 写的时候在末尾追加,指针移到到最后
# 大家一定要清楚的明白读写的时候指针指向的位置,下面的这个例子一定要懂
# f.tell() 读取指针的位置
# f.seek(0) 设置指针的位置
with open('1.txt','r+',encoding='utf-8') as f:
print(f.tell()) #打印下 文件开始时候指针指向哪里 这里指向 0
print(f.read()) #读出文件内容'字符串',
print(f.tell()) #文件指针指到 9,一个汉子三个字符串,指针是以字符为单位
f.write('科比') #写入内容'科比',需要特别注意此时文件指到文件末尾去了
print(f.read()) #指针到末尾去了,所以读取的内容为空
print(f.tell()) #指针指到15
f.seek(0) #将指针内容指到 0 位置
print(f.read()) #因为文件指针指到开头去了,所以可以读到内容 字符串科比 # w+形式 存在的话先清空 一写的时候指针到最后
with open('1.txt','w+') as f:
f.write('Kg') #1.txt存在,所以将内面的内容清空,然后再写入 'kg'
print(f.tell()) #此时指针指向2
print(f.read()) #读不到内容,因为指针指向末尾了
f.seek(0)
print(f.read()) #读到内容,因为指针上一步已经恢复到起始位置 # a+打开的时候指针已经移到最后,写的时候不管怎样都往文件末尾追加,这里就不再演示了,读者可以自己试一下
# x+文件存在的话则报错,也不演示了

“b”表示以字节的方式操作

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

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

文件 hello.txt
Hello Word!
abc
abc
abc代码 :
f = open("hello.txt",'rb') # 用到b模式的时候 就不能跟 编码了。
data = f.read()
f.close()
print(data)输出
C:\Python35\python3.exe E:/py_test/s5/open.py
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 的区别

Python全栈之路4–内置函数–文件操作

用‘+’同时读写某一个文件

# r+形式 写的时候在末尾追加,指针移到到最后
# 大家一定要清楚的明白读写的时候指针指向的位置,下面的这个例子一定要懂
# f.tell() 读取指针的位置
# f.seek(0) 设置指针的位置
with open('1.txt','r+',encoding='utf-8') as f:
print(f.tell()) #打印下 文件开始时候指针指向哪里 这里指向 0
print(f.read()) #读出文件内容'字符串',
print(f.tell()) #文件指针指到 9,一个汉子三个字符串,指针是以字符为单位
f.write('科比') #写入内容'科比',需要特别注意此时文件指到文件末尾去了
print(f.read()) #指针到末尾去了,所以读取的内容为空
print(f.tell()) #指针指到15
f.seek(0) #将指针内容指到 0 位置
print(f.read()) #因为文件指针指到开头去了,所以可以读到内容 字符串科比 # w+形式 存在的话先清空 一写的时候指针到最后
with open('1.txt','w+') as f:
f.write('Kg') #1.txt存在,所以将内面的内容清空,然后再写入 'kg'
print(f.tell()) #此时指针指向2
print(f.read()) #读不到内容,因为指针指向末尾了
f.seek(0)
print(f.read()) #读到内容,因为指针上一步已经恢复到起始位置 # a+打开的时候指针已经移到最后,写的时候不管怎样都往文件末尾追加,这里就不再演示了,读者可以自己试一下
# x+文件存在的话则报错,也不演示了

python 文件的读取方式

Python全栈之路4–内置函数–文件操作

5.2  操作

class TextIOWrapper(_TextIOBase):
"""
Character and line based layer over a BufferedIOBase object, buffer. encoding gives the name of the encoding that the stream will be
decoded or encoded with. It defaults to locale.getpreferredencoding(False). errors determines the strictness of encoding and decoding (see
help(codecs.Codec) or the documentation for codecs.register) and
defaults to "strict". newline controls how line endings are handled. It can be None, '',
'\n', '\r', and '\r\n'. It works as follows: * On input, if newline is None, universal newlines mode is
enabled. Lines in the input can end in '\n', '\r', or '\r\n', and
these are translated into '\n' before being returned to the
caller. If it is '', universal newline mode is enabled, but line
endings are returned to the caller untranslated. If it has any of
the other legal values, input lines are only terminated by the given
string, and the line ending is returned to the caller untranslated. * On output, if newline is None, any '\n' characters written are
translated to the system default line separator, os.linesep. If
newline is '' or '\n', no translation takes place. If newline is any
of the other legal values, any '\n' characters written are translated
to the given string. If line_buffering is True, a call to flush is implied when a call to
write contains a newline character.
"""
def close(self, *args, **kwargs): # real signature unknown
关闭文件
pass def fileno(self, *args, **kwargs): # real signature unknown
文件描述符
pass def flush(self, *args, **kwargs): # real signature unknown
刷新文件内部缓冲区
pass def isatty(self, *args, **kwargs): # real signature unknown
判断文件是否是同意tty设备
pass def read(self, *args, **kwargs): # real signature unknown
读取指定字节数据
pass def readable(self, *args, **kwargs): # real signature unknown
是否可读
pass def readline(self, *args, **kwargs): # real signature unknown
仅读取一行数据
pass def seek(self, *args, **kwargs): # real signature unknown
指定文件中指针位置
pass def seekable(self, *args, **kwargs): # real signature unknown
指针是否可操作
pass def tell(self, *args, **kwargs): # real signature unknown
获取指针位置
pass def truncate(self, *args, **kwargs): # real signature unknown
截断数据,仅保留指定之前数据
pass def writable(self, *args, **kwargs): # real signature unknown
是否可写
pass def write(self, *args, **kwargs): # real signature unknown
写内容
pass def __getstate__(self, *args, **kwargs): # real signature unknown
pass def __init__(self, *args, **kwargs): # real signature unknown
pass @staticmethod # known case of __new__
def __new__(*args, **kwargs): # real signature unknown
""" Create and return a new object. See help(type) for accurate signature. """
pass def __next__(self, *args, **kwargs): # real signature unknown
""" Implement next(self). """
pass def __repr__(self, *args, **kwargs): # real signature unknown
""" Return repr(self). """
pass buffer = property(lambda self: object(), lambda self, v: None, lambda self: None) # default closed = property(lambda self: object(), lambda self, v: None, lambda self: None) # default encoding = property(lambda self: object(), lambda self, v: None, lambda self: None) # default errors = property(lambda self: object(), lambda self, v: None, lambda self: None) # default line_buffering = property(lambda self: object(), lambda self, v: None, lambda self: None) # default name = property(lambda self: object(), lambda self, v: None, lambda self: None) # default newlines = property(lambda self: object(), lambda self, v: None, lambda self: None) # default _CHUNK_SIZE = property(lambda self: object(), lambda self, v: None, lambda self: None) # default _finalizing = property(lambda self: object(), lambda self, v: None, lambda self: None) # default

3.x的文件操作

class file(object)
def close(self): # real signature unknown; restored from __doc__
关闭文件
"""
close() -> None or (perhaps) an integer. Close the file. Sets data attribute .closed to True. A closed file cannot be used for
further I/O operations. close() may be called more than once without
error. Some kinds of file objects (for example, opened by popen())
may return an exit status upon closing.
""" def fileno(self): # real signature unknown; restored from __doc__
文件描述符
"""
fileno() -> integer "file descriptor". This is needed for lower-level file interfaces, such os.read().
"""
return 0 def flush(self): # real signature unknown; restored from __doc__
刷新文件内部缓冲区
""" flush() -> None. Flush the internal I/O buffer. """
pass def isatty(self): # real signature unknown; restored from __doc__
判断文件是否是同意tty设备
""" isatty() -> true or false. True if the file is connected to a tty device. """
return False def next(self): # real signature unknown; restored from __doc__
获取下一行数据,不存在,则报错
""" x.next() -> the next value, or raise StopIteration """
pass def read(self, size=None): # real signature unknown; restored from __doc__
读取指定字节数据
"""
read([size]) -> read at most size bytes, returned as a string. If the size argument is negative or omitted, read until EOF is reached.
Notice that when in non-blocking mode, less data than what was requested
may be returned, even if no size parameter was given.
"""
pass def readinto(self): # real signature unknown; restored from __doc__
读取到缓冲区,不要用,将被遗弃
""" readinto() -> Undocumented. Don't use this; it may go away. """
pass def readline(self, size=None): # real signature unknown; restored from __doc__
仅读取一行数据
"""
readline([size]) -> next line from the file, as a string. Retain newline. A non-negative size argument limits the maximum
number of bytes to return (an incomplete line may be returned then).
Return an empty string at EOF.
"""
pass def readlines(self, size=None): # real signature unknown; restored from __doc__
读取所有数据,并根据换行保存值列表
"""
readlines([size]) -> list of strings, each a line from the file. Call readline() repeatedly and return a list of the lines so read.
The optional size argument, if given, is an approximate bound on the
total number of bytes in the lines returned.
"""
return [] def seek(self, offset, whence=None): # real signature unknown; restored from __doc__
指定文件中指针位置
"""
seek(offset[, whence]) -> None. Move to new file position. Argument offset is a byte count. Optional argument whence defaults to
(offset from start of file, offset should be >= 0); other values are 1
(move relative to current position, positive or negative), and 2 (move
relative to end of file, usually negative, although many platforms allow
seeking beyond the end of a file). If the file is opened in text mode,
only offsets returned by tell() are legal. Use of other offsets causes
undefined behavior.
Note that not all file objects are seekable.
"""
pass def tell(self): # real signature unknown; restored from __doc__
获取当前指针位置
""" tell() -> current file position, an integer (may be a long integer). """
pass def truncate(self, size=None): # real signature unknown; restored from __doc__
截断数据,仅保留指定之前数据
"""
truncate([size]) -> None. Truncate the file to at most size bytes. Size defaults to the current file position, as returned by tell().
"""
pass def write(self, p_str): # real signature unknown; restored from __doc__
写内容
"""
write(str) -> None. Write string str to file. Note that due to buffering, flush() or close() may be needed before
the file on disk reflects the data written.
"""
pass def writelines(self, sequence_of_strings): # real signature unknown; restored from __doc__
将一个字符串列表写入文件
"""
writelines(sequence_of_strings) -> None. Write the strings to the file. Note that newlines are not added. The sequence can be any iterable object
producing strings. This is equivalent to calling write() for each string.
"""
pass def xreadlines(self): # real signature unknown; restored from __doc__
可用于逐行读取文件,非全部
"""
xreadlines() -> returns self. For backward compatibility. File objects now include the performance
optimizations previously implemented in the xreadlines module.
"""
pass

2.x Code

操作演示:

hello.txt  文件内容

Hello Word!
123
abc
456
abc
789
abc

read 方法:

# 以只读的方式打开文件hello.txt
f = open("hello.txt","r")
# 读取文件内容赋值给变量c
c = f.read()
# 关闭文件
f.close()
# 输出c的值
print(c)输出结果
C:\Python35\python3.exe E:/py_test/s5/open.py
Hello Word!
abc
abc
abc

readline

# 以只读模式打开文件hello.txt
f = open("hello.txt","r")
# 读取第一行 strip 去除空行
c1 = f.readline().strip()
# 读取第二行
c2 = f.readline().strip()
# 读取第三行
c3 = f.readline().strip()
# 关闭文件
f.close()
# 输出读取文件第一行内容
print(c1)
# 输出读取文件第二行内容
print(c2)
# 输出读取文件第三行内容
print(c3)C:\Python35\python.exe F:/Python_code/sublime/Day06/file.py
Hello Word!
abc

readlines 获取到的是列表的形式,每一行的都是列表的元素:

# 以只读的方式打开文件hello.txt
f = open("hello.txt","r")
# 将文件所有内容赋值给c
c = f.readlines()
# 查看数据类型
print(type(c))
# 关闭文件
f.close()
# 遍历输出文件内容 # n.strip()去除空行
for n in c:
print(n.strip())

python的写入方式:

Python全栈之路4–内置函数–文件操作

write

# 以只读的模式打开文件write.txt,没有则创建,有则覆盖内容
file = open("write.txt","w")
# 在文件内容中写入字符串test write
file.write("test write")
# 关闭文件
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的文件内容》》》123456

python 文件操作提供的方法

close(self)

  关闭已经打开的文件

f.close()

fileno(self)   文件描述

f = open('hello.txt', 'rb')data = f.fileno()f.close()print(data)>>> 33333

flush(self)

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

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

isatty(self)

判断文件是否是tty设备,如果是tty设备则返回 True ,否则返回 False

readable(self)

否可读,如果可读返回 True ,否则返回 False

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

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

tell(self) 获取指针的当前位置

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

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

结果:》》》0   3

writeable(self)   是否可写;  返回值是  True   False

writelines(self, lines):

写入文件的字符串序列,序列可以是任意迭代的对象,通常是一个字符串列表

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

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

Practice:操作  文件内容替换

文件内容的替换  fileinput.input注意
改文件内容 有inplace=1
没有inplace=1 原始文件不会被修改。不写的话默认=0 输出显示改掉,文件不该掉
、最后改完print
最后必须print 一下。不然会全部清空查看源文件
root@python:/home/liujianzuo/py_training/seminar6/day2# cat filehandle1.py
#!/usr/bin/env pythonf = file('syslog')#for line in f.xreadlines():
# print line,
# print break
while True:
line = f.readlines()
print line,
if not line:break
root@python:/home/liujianzuo/py_training/seminar6/day2# python
Python 2.7.6 (default, Mar 22 2014, 22:59:56)
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import tab
>>> import fileinput
>>> import fileinput,tab
>>> for line in fileinput.input('filehandle1.py',inplace=1):
... line = line.replace('break','continue') # 注意tab或者空格换行
... print line,
... ##直接回车操作完查看
root@python:/home/liujianzuo/py_training/seminar6/day2# cat filehandle1.py.bak
#!/usr/bin/env pythonf = file('syslog')#for line in f.xreadlines():
# print line,
# print continue
while True:
line = f.readlines()
print line,
if not line:continue2.1 课上 新的替换问价内容的方法
root@python-10:~# cd /home/liujianzuo/python/day2/
root@python-10:/home/liujianzuo/python/day2# ls
chinese.py ex2.py __init__.py py_home_work.csv second.pyc
ex1.py ex3_file_io.py __init__.pyc second.py test
root@python-10:/home/liujianzuo/python/day2# cp /etc/passwd .#!/usr/bin/env pythonimport sys
if '-r' in sys.argv: #判断 输入的 -r 是在参数位置
rep_argv_pos = sys.argv.index('-r') #赋值-r 索引位置
find_str = sys.argv[rep_argv_pos + 1]
new_str = sys.argv[rep_argv_pos + 2]
f = file('passwd','r+')
while True:
line = f.readline()
print "===>",f.tell()
if find_str in line:
print '---> cur pos',f.tell(),len(line)
last_line_pos=f.tell() - len(line)
f.seek(last_line_pos)
print '----> new pos',f.tell()
new_line= line.replace(find_str,new_str)
f.write(new_line)
break
f.close()root@python-10:/home/liujianzuo/python/day2# py replace_new.py -r root ROOT
===> 32
---> cur pos 32 32
----> new pos 0
root@python-10:/home/liujianzuo/python/day2# head -1 passwd
ROOT:x:0:0:ROOT:/ROOT:/bin/bash
更改文件内容前备份 backup=‘。Bak’
>>> help(fileinput)
class FileInput
| FileInput([files[, inplace[, backup[, bufsize[, mode[, openhook]]]]]])
|
| Class FileInput is the implementation of the module; its methods
| filename(), lineno(), fileline(), isfirstline(), isstdin(), fileno(),
| nextfile() and close() correspond to the functions of the same name
| in the module.
| In addition it has a readline() method which returns the next
| input line, and a __getitem__() method which implements the
| sequence behavior. The sequence must be accessed in strictly
| sequential order; random access and readline() cannot be mixed.
|
| Methods defined here:
|
| __del__(self)
|
| __getitem__(self, i)
|
| __init__(self, files=None, inplace=0, backup='', bufsize=0, mode='r', openhook=None)操作:
最后不带print
>>> for line in fileinput.input('filehandle1.py',inplace=1,backup='.bak'):
... line = line.replace('continue','break')
...
>>>
root@python:/home/liujianzuo/py_training/seminar6/day2# ls
filehandle1.py filehandle1.py.bak filehandle.py syslog test.txt zh-CN.zip
root@python:/home/liujianzuo/py_training/seminar6/day2# cat filehandle1.py
#内容被清除掉了我们将备份恢复进行再次备份操作
root@python:/home/liujianzuo/py_training/seminar6/day2# cp filehandle1.py.bak filehandle1.py
root@python:/home/liujianzuo/py_training/seminar6/day2# cat filehandle1.py
#!/usr/bin/env pythonf = file('syslog')#for line in f.xreadlines():
# print line,
# print continue
while True:
line = f.readlines()
print line,
if not line:continue
再次执行
>>> for line in fileinput.input('filehandle1.py',inplace=1,backup='.bak1'):
... line = line.replace('continue','TERWTREW')
... print line,
...
再次检查
root@python:/home/liujianzuo/py_training/seminar6/day2# ls
filehandle1.py filehandle1.py.bak filehandle1.py.bak1 filehandle.py syslog test.txt zh-CN.zip
root@python:/home/liujianzuo/py_training/seminar6/day2# cat filehandle1.py
#!/usr/bin/env pythonf = file('syslog')#for line in f.xreadlines():
# print line,
# print TERWTREW
while True:
line = f.readlines()
print line,
if not line:TERWTREW

文件内容的替换 fileinput.input

六、管理上下文

为了避免打开文件之后忘记关闭,我们通常使用:

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

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

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

with open('log1') as obj1, open('log2') as obj2:
pass
# 文件句柄可以循环,每次1句,写入 另一个文件
with open('hello.txt','r') as obj1 ,open('log2','w') as obj2:
for line in obj1:
obj2.write(line)

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

#!/usr/bin/env python
# _*_ coding:utf-8 _*_
__author__ = 'liujianzuo'def login(username,password):
"""
用户验证
:param username: 用户名
:param password: 密码
:return: true 成功 false 失败
"""
f = open("db",'r')
for line in f:
line=line.strip()
line=line.split(":")
if username == line[0] and password == line[1]:
return True
return Falsedef register(temp):
"""
注册写入
:param temp: 写入的用户名密码
:return: true是注册成功
"""
with open('db','a+',encoding='utf-8') as f:
f.write(temp)
return True
def user_exist(username):
"""
判断用户存在并调用注册
:param username:
:return: true 是注册成功 false 是用户存在
"""
with open('db','r',encoding='utf-8') as f:
for line in f:
if username == line.strip().split(':')[0]:
#print("exist")
return False
else:
pwd = input("pls input pwd:")
temp = "\n"+username+":"+pwd
a = register(temp)
if a:
#print("register success")
return Truedef changepwd():
"""
改密码
:return: True 改成功了 False 用户不存在
"""
# import fileinput
# username = input("input ur username:")
# f = open('db','r+',)
# #print(type(username))
# for line in f:
# line = line.strip().split(':')
# #print(type(line[1]))
# #line[1] = str(line[1])
# if line[0] == username:
# pwd = input("chage ur 原来的 passwd:")
# if line[1] != pwd:
# print("not creect")
# return "原密码不对"
# f.close()
#
# new_pwd = input('chage ur new pwd:')
# # print(username+":"+new_pwd)
# # exit()
# for n in fileinput.input('db',inplace=1):
# #x = n.strip().split(':')
# n = n.replace(username+":"+pwd,username+":"+new_pwd).strip()
# print(n)
# return True
f = open('db','r')
data = f.readlines()
f.close()
username = input("pls input username:")
#print(data)
for i in range(len(data)):
if username == data[i].split(":")[0]:
pwd = input("input new passwd:")
data[i] = username+":"+pwd+"\n"
n = open('db','w+')
n.writelines(data)
return Truedef dele():
"""
删除用户
:return:
"""
f = open('db','r')
data = f.readlines()
f.close()
username = input("pls input username:")
#print(data)
for i in range(len(data)):
if username == data[i].split(":")[0]:
#pwd = input("input new passwd:")
del data[i]
n = open('db','w+')
n.writelines(data)
return Truedef chs(chose):
"""
选择菜单
:param chose:
:return:
"""
if chose == 1:
user = input("pls input username:")
pwd = input("pls input password:") ret = login(user,pwd)
if ret:
print("登陆成功")
else:
print("登陆失败")
elif chose == 2:
user = input("register name:")
n = user_exist(user)
if n:
print("regist success")
else:
print("usernaem exist")
elif chose == 3:
ret = changepwd()
if ret:
print("修改成功") elif chose == 4:
ret = dele()
if ret:
print("删除成功") else:
print("chose not correct")
def confirm(chose):
"""
判断输入
:param chose:
:return:
"""
while True:
if len(chose) == 0:
print("\033[31;1mnot empty!!!!\033[0m")
chose = input("\033[35;1mpls input ur chose ,quit for leave:\033[0m")
continue
elif chose == 'quit':
return True
elif chose.isdigit() != True:
print("\033[31;1minput digit!!!!\033[0m")
chose = input("\033[35;1mpls input ur chose ,quit for leave:\033[0m")
continue
else:
breakdef main():
print("""\033[32;1m
1 login
2 register
3 忘记密码
4 删除用户
\033[0m""")
chose = input("\033[35;1mpls input ur chose ,quit for leave:\033[0m")
ret = confirm(chose)
if ret:
print("will quit")
return ret
chose=int(chose)
chs(chose)if __name__ == "__main__":
main()

利用内置函数chr(),ord()以及random模块写一个简单随机4位验证码:

import random
tmp=''                            #最后生成的随机码
for i in range(4):
n=random.randrange(0,2)                #生成随机数1或0,用来判断下面,是生成随机数字,还是字母
if n==0:
num = random.randrange(65, 91)         #为0时候,生成大写字母
tmp+=chr(num)
else:
k=random.randrange(0,10)             #为1时候,生成数字
tmp+=str(k)
print(tmp)                         #这里运行的时候每次生成的4为随机码都不同

初探递归:

  如果一个函数在其内部调用它自己,就叫做递归,但是递归的时候要设置一个退出递归的条件,不然会一直递归下去,变成一个死循环。从另一个方面来说,递归其实和循环其实是等价的。想要明白递归的话,我们先从实际的例子上来说明这一点,比如说我们要写一个阶乘函数 f(n)算出n的阶乘,阶乘函数实现的方法很多,下面讲如何用递归实现。

def f(n):
if 0==n:   # n=0 的话直接返回空,对用户输入的零进行判断
return None
elif 1==n:   # n=1 的话就不再递归
return n
else:
return n*f(n-1)   # 递归在执行f(n-1) 直到f(1)
print(f(5))   # 120
'''
f(5)的执行过程如下
===> f(5)
===> 5 * f(4)
===> 5 * (4 * f(3))
===> 5 * (4 * (3 * f(2)))
===> 5 * (4 * (3 * (2 * f(1))))
===> 5 * (4 * (3 * (2 * 1)))
===> 5 * (4 * (3 * 2))
===> 5 * (4 * 6)
===> 5 * 24
===> 120
'''

上一篇随笔的最后一个作业,就是用递归获取斐波那契数列中的第10个数,这里我们来说说是怎么实现的,费波那契数列由0,1开始,费波那契系数就由之前的两数相加,先看代码,

def fun(n):               # fun(10)即可计算第十个斐波拉数
if 1==n :              #直接定义前面两个数为 0 ,1,如果输入的n为1,2的话直接就返回了
return 0
elif 2==n:
return 1
else:
return fun(n-1)+fun(n-2)   #如果输入的不是1,2则进行递归出来计算他前面两个数的和 '''
fun(5)的执行过程如下
===> fun(5)
===> fun(4)+fun(3)
===> fun(3)+fun(2) + fun(2)+fun(1)
===> fun(2)+fun(1)+fun(2)+fun(2)+fun(1)
===> 1+0+1+1+1+0
===> 3
'''
相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,111
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,584
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,431
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,203
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,838
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,922