1、Set基本数据类型

a、set集合,是一个无序且不重复的元素集合

  1. class set(object):
  2. """
  3. set() -> new empty set object
  4. set(iterable) -> new set object
  5.  
  6. Build an unordered collection of unique elements.
  7. """
  8. def add(self, *args, **kwargs): # real signature unknown
  9. """
  10. Add an element to a set,添加元素
  11.  
  12. This has no effect if the element is already present.
  13. """
  14. pass
  15.  
  16. def clear(self, *args, **kwargs): # real signature unknown
  17. """ Remove all elements from this set. 清楚内容"""
  18. pass
  19.  
  20. def copy(self, *args, **kwargs): # real signature unknown
  21. """ Return a shallow copy of a set. 浅拷贝 """
  22. pass
  23.  
  24. def difference(self, *args, **kwargs): # real signature unknown
  25. """
  26. Return the difference of two or more sets as a new set. A中存在,B中不存在
  27.  
  28. (i.e. all elements that are in this set but not the others.)
  29. """
  30. pass
  31.  
  32. def difference_update(self, *args, **kwargs): # real signature unknown
  33. """ Remove all elements of another set from this set. 从当前集合中删除和B中相同的元素"""
  34. pass
  35.  
  36. def discard(self, *args, **kwargs): # real signature unknown
  37. """
  38. Remove an element from a set if it is a member.
  39.  
  40. If the element is not a member, do nothing. 移除指定元素,不存在不保错
  41. """
  42. pass
  43.  
  44. def intersection(self, *args, **kwargs): # real signature unknown
  45. """
  46. Return the intersection of two sets as a new set. 交集
  47.  
  48. (i.e. all elements that are in both sets.)
  49. """
  50. pass
  51.  
  52. def intersection_update(self, *args, **kwargs): # real signature unknown
  53. """ Update a set with the intersection of itself and another. 取交集并更更新到A中 """
  54. pass
  55.  
  56. def isdisjoint(self, *args, **kwargs): # real signature unknown
  57. """ Return True if two sets have a null intersection. 如果没有交集,返回True,否则返回False"""
  58. pass
  59.  
  60. def issubset(self, *args, **kwargs): # real signature unknown
  61. """ Report whether another set contains this set. 是否是子序列"""
  62. pass
  63.  
  64. def issuperset(self, *args, **kwargs): # real signature unknown
  65. """ Report whether this set contains another set. 是否是父序列"""
  66. pass
  67.  
  68. def pop(self, *args, **kwargs): # real signature unknown
  69. """
  70. Remove and return an arbitrary set element.
  71. Raises KeyError if the set is empty. 移除元素
  72. """
  73. pass
  74.  
  75. def remove(self, *args, **kwargs): # real signature unknown
  76. """
  77. Remove an element from a set; it must be a member.
  78.  
  79. If the element is not a member, raise a KeyError. 移除指定元素,不存在保错
  80. """
  81. pass
  82.  
  83. def symmetric_difference(self, *args, **kwargs): # real signature unknown
  84. """
  85. Return the symmetric difference of two sets as a new set. 对称交集
  86.  
  87. (i.e. all elements that are in exactly one of the sets.)
  88. """
  89. pass
  90.  
  91. def symmetric_difference_update(self, *args, **kwargs): # real signature unknown
  92. """ Update a set with the symmetric difference of itself and another. 对称交集,并更新到a中 """
  93. pass
  94.  
  95. def union(self, *args, **kwargs): # real signature unknown
  96. """
  97. Return the union of sets as a new set. 并集
  98.  
  99. (i.e. all elements that are in either set.)
  100. """
  101. pass
  102.  
  103. def update(self, *args, **kwargs): # real signature unknown
  104. """ Update a set with the union of itself and others. 更新 """
  105. pass

set

b、数据类型模块举例

  1. se = {11,22,33,44,55}
  2. be = {44,55,66,77,88}
  3.  
  4. # se.add(66)
  5. # print(se) #添加元素,不能直接打印!
  6. #
  7. #
  8. #
  9. # se.clear()
  10. # print(se) #清除se集合里面所有的值,不能清除单个
  11. #
  12. #
  13. #
  14. # ce=be.difference(se) #se中存在,be中不存在的值,必须赋值给一个新的变量
  15. # print(ce)
  16. #
  17. #
  18. # se.difference_update(be)
  19. # print(se) #在se中删除和be相同的值,不能赋值给一个新的变量,先输入转换,然后打印,也不能直接打印!
  20.  
  21. # se.discard(11)
  22. # print(se) #移除指定元素,移除不存在的时候,不会报错
  23.  
  24. # se.remove(11)
  25. # print(se) #移除指定的元素,移除不存在的会报错
  26.  
  27. # se.pop()
  28. # print(se) #移除随机的元素
  29. #
  30. #
  31. # ret=se.pop()
  32. # print(ret) #移除元素,并且可以把移除的元素赋值给另一个变量
  33.  
  34. # ce = se.intersection(be)
  35. # print(ce) #取出两个集合的交集(相同的元素)
  36.  
  37. # se.intersection_update(be)
  38. # print(se) #取出两个集合的交集,并更新到se集合中
  39.  
  40. # ret = se.isdisjoint(be)
  41. # print(ret) #判断两个集合之间又没有交集,如果有交集返回False,没有返回True
  42.  
  43. # ret=se.issubset(be)
  44. # print(ret) #判断se是否是be集合的子序列,如果是返回True,不是返回Flase
  45.  
  46. # ret = se.issuperset(be)
  47. # print(ret) #判断se是不是be集合的父序列,如果是返回True,不是返回Flase
  48.  
  49. # ret=se.symmetric_difference(be)
  50. # print(ret) #对称交集,取出除了不相同的元素
  51.  
  52. # se.symmetric_difference_update(be)
  53. # print(se) #对称交集,取出不相同的元素并更新到se集合中
  54.  
  55. # ret = se.union(be)
  56. # print(ret) #并集,把两个元素集合并在一个新的变量中
2、深浅拷贝

a、数字和字符串

对于 数字 和 字符串 而言,赋值、浅拷贝和深拷贝无意义,因为其永远指向同一个内存地址。

  1. import copy
  2. # ######### 数字、字符串 #########
  3. n1 = 123
  4. # n1 = "i am alex age 10"
  5. print(id(n1))
  6. # ## 赋值 ##
  7. n2 = n1
  8. print(id(n2))
  9. # ## 浅拷贝 ##
  10. n2 = copy.copy(n1)
  11. print(id(n2))
  12.  
  13. # ## 深拷贝 ##
  14. n3 = copy.deepcopy(n1)
  15. print(id(n3))

 b、其他基本数据类型

对于字典、元祖、列表 而言,进行赋值、浅拷贝和深拷贝时,其内存地址的变化是不同的。

1、赋值

赋值,只是创建一个变量,该变量指向原来内存地址,如:

  1. n1 = {"k1": "zhangyanlin", "k2": 123, "k3": ["Aylin", 456]}
  2.  
  3. n2 = n1

 

2、浅拷贝

浅拷贝,在内存中只额外创建第一层数据

  1. import copy
  2.  
  3. n1 = {"k1": "zhangyanlin", "k2": 123, "k3": ["aylin", 456]}
  4.  
  5. n3 = copy.copy(n1)

  

3、深拷贝

深拷贝,在内存中将所有的数据重新创建一份(排除最后一层,即:python内部对字符串和数字的优化)

3、函数
  • 函数式:将某功能代码封装到函数中,日后便无需重复编写,仅调用函数即可
  • 面向对象:对函数进行分类和封装,让开发“更快更好更强...
  • 函数传参数传的是引用

.函数的定义主要有如下要点:

  • def:表示函数的关键字
  • 函数名:函数的名称,日后根据函数名调用函数
  • 函数体:函数中进行一系列的逻辑计算,如:发送邮件、计算出 [11,22,38,888,2]中的最大数等...
  • 参数:为函数体提供数据
  • 返回值:当函数执行完毕后,可以给调用者返回数据。

1、返回值

函数是一个功能块,该功能到底执行成功与否,需要通过返回值来告知调用者。

以上要点中,比较重要有参数和返回值:

  1. def 发送短信():
  2.  
  3. 发送短信的代码...
  4.  
  5. if 发送成功:
  6. return True
  7. else:
  8. return False
  9.  
  10. while True:
  11.  
  12. # 每次执行发送短信函数,都会将返回值自动赋值给result
  13. # 之后,可以根据result来写日志,或重发等操作
  14.  
  15. result = 发送短信()
  16. if result == False:
  17. 短信发送失败...

  

函数的有三中不同的参数:

  • 普通参数
  1. # ######### 定义函数 #########
  2.  
  3. # name 叫做函数func的形式参数,简称:形参
  4. def func(name):
  5. print name
  6.  
  7. # ######### 执行函数 #########
  8. # 'zhangyanlin' 叫做函数func的实际参数,简称:实参
  9. func('zhangyanlin')

  

  • 默认参数
  1. def func(name, age = 18):
  2.  
  3. print "%s:%s" %(name,age)
  4.  
  5. # 指定参数
  6. func('zhangyanlin', 19)
  7. # 使用默认参数
  8. func('nick')
  9.  
  10. 注:默认参数需要放在参数列表最后

  

  • 动态参数
  1. def func(*args):
  2.  
  3. print args
  4.  
  5. # 执行方式一
  6. func(11,33,4,4454,5)
  7.  
  8. # 执行方式二
  9. li = [11,2,2,3,3,4,54]
  10. func(*li)

  

  1. def func(**kwargs):
  2.  
  3. print args
  4.  
  5. # 执行方式一
  6. func(name'wupeiqi',age=18)
  7.  
  8. # 执行方式二
  9. li = {'name':'wupeiqi', age:18, 'gender':'male'}
  10. func(**li)

  

  1. def func(*args, **kwargs):
  2.  
  3. print args
  4. print kwargs

邮件实例:

  1. def email(p,j,k):
  2. import smtplib
  3. from email.mime.text import MIMEText
  4. from email.utils import formataddr
  5.  
  6. set = True
  7. try:
  8. msg = MIMEText('j', 'plain', 'utf-8') #j 邮件内容
  9. msg['From'] = formataddr(["武沛齐",'wptawy@126.com'])
  10. msg['To'] = formataddr(["走人",'424662508@qq.com'])
  11. msg['Subject'] = "k" #k主题
  12.  
  13. server = smtplib.SMTP("smtp.126.com", 25)
  14. server.login("wptawy@126.com", "WW.3945.59")
  15. server.sendmail('wptawy@126.com', [p], msg.as_string())
  16. server.quit()
  17. except:
  18. set = False
  19. return True
  20.  
  21. formmail = input("请你输入收件人邮箱:")
  22. zhuti = input("请您输入邮件主题:")
  23. neirong = input("请您输入邮件内容:")
  24. aa=email(formmail,neirong,zhuti)
  25. if aa:
  26. print("邮件发送成功!")
  27. else:
  28. print("邮件发送失败!")

2、 内置函数

  1. # abs绝对值
  2. # i = abs(-123)
  3. # print(i) #返回123,绝对值
  4.  
  5. # #all,循环参数,如果每个元素为真,那么all返回的为真,有一个为假返回的就是假的
  6. # a = all((None,123,456,False))
  7. # print(a) #返回的为假的,证明中间有False值
  8. #
  9. # #所有的假值有
  10. # #0,None,空值
  11. #
  12.  
  13. # #any 只要之前有一个是真的,返回的就是真
  14. # b = any([11,False])
  15. # print(b)
  16.  
  17. #ascii,去指定对象的类中找__repr__,获取返回值
  18. # #ascii函数
  19. # class Foo:
  20. # def __repr__(self):
  21. # return "zhangyanlin"
  22. # obj =Foo()
  23. # r = ascii(obj)
  24. # print(r)
  25.  
  26. # 布尔值返回真或假
  27. # print(bool(1))
  28. # print(bool(0))
  29.  
  30. # #bin二进制
  31. # r = bin(123)
  32. # print(r)
  33.  
  34. # #oct八进制
  35. # r = oct(123)
  36. # print(r)
  37.  
  38. # #int十进制
  39. # r = int(123)
  40. # print(r)
  41.  
  42. # #hex十六进制
  43. # r = hex(123)
  44. # print(r)
  45.  
  46. # #二进制转十进制
  47. # i= int("0b11",base=2)
  48. # print(i)
  49.  
  50. # #八进制转十进制
  51. # i= int("11",base=8)
  52. # print(i)
  53.  
  54. # #十六进制转十进制
  55. # i = int("0xe",base=16)
  56. # print(i)
  57.  
  58. # #数字代表字母
  59. # c = chr(66)
  60. # print(c)
  61.  
  62. # #字母代表数字
  63. # c = ord("a")
  64. # print(c)
  65.  
  66. #bytes, 字节
  67. #字节和字符串的转换
  68. # a = bytes("zhangyanlin",encoding="utf-8")
  69. # print(a)
  70. #bytearray 字节列表
  71.  
  72. #chr(),把数字转换成字母,只适用于ascii码
  73. # a = chr(65)
  74. # print(a)
  75.  
  76. #ord(),把字母转换成数字,只适用于ascii码
  77. # a = ord("a")
  78. # print(a)
  79.  
  80. #callable表示一个对象是否可执行
  81. # def f1(): #看这个函数能不能执行,能发挥True
  82. # return 123
  83. # f1()
  84. # r = callable(f1)
  85. # print(r)
  86.  
  87. #dir,查看一个类里面存在的功能
  88. # li = []
  89. # print(dir(li))
  90. # help(list)
  91.  
  92. #divmod(),#分页的时候使用
  93. # a = 10/3
  94. # r = divmod(10,3)
  95. # print(r)
  96.  
  97. #compile编译, 把字符串转移成python可执行的代码,知道就行
  98.  
  99. #eval(),简单的表达式,可以给算出来
  100. # b = eval("a + 69" , {"a":99}) #a可以通过字典声明变量去写入
  101. # print(b)
  102.  
  103. #exec,不会返回值,直接输出结果
  104. # exec("for i in range(10):print(i)")
  105.  
  106. # filter对于序列中的元素进行筛选,最终获取符合条件的序列(需要循环)
  107. # def f1(x):
  108. # if x >22:
  109. # return True
  110. # else:
  111. # return False
  112. #
  113. # ret = filter(f1,[11,22,33,44,55])
  114. # for i in ret:
  115. # print(i)
  116.  
  117. # ret = filter(lambda x: x > 22, [11, 22, 33, 44, 55, 66, 77])
  118. # for i in ret:
  119. # print(i)
  120.  
  121. #map(函数,可以迭代的对象,让元素统一操作)
  122. # def f1(x):
  123. # return x+123
  124. #
  125. # # li = [11,22,33,44,55,66]
  126. # # ret = map(f1,li)
  127. # print(ret)
  128. # for i in ret:
  129. # print(i)
  130. #
  131. # ret = map(lambda x: x + 100 if x%2==1 else x, [11, 22, 33, 44])
  132. # print(ret)
  133. # for i in ret:
  134. # print(i)
  135.  
  136. #globals()获取当前所有的全局变量
  137.  
  138. #locals()获取当前所有的局部变量
  139. # ret = "kaszhfiusdhf"
  140. # def fu1():
  141. # name = 123
  142. # print(locals())
  143. # print(globals())
  144. #
  145. # fu1()
  146.  
  147. #hash 对key的优化,相当于给输出一种哈希值
  148. # li = "sdglgmdgongoaerngonaeorgnienrg"
  149. # print(hash(li))
  150.  
  151. #isinstance()判断是不是一个类型
  152. # li = [11,22]
  153. # ret = isinstance(li,list)
  154. # print(ret)
  155.  
  156. #iter创建一个可以被迭代的元素
  157. # obj = iter([11,22,33,44])
  158. # print(obj)
  159. # #next,取下一个值,一个变量里的值可以一直往下取,直到没有就报错
  160. # ret = next(obj)
  161.  
  162. #max()取最大的值
  163. # li = [11,22,33,44]
  164. # ret = max(li)
  165. # print(ret)
  166.  
  167. #min()取最小值
  168. # li = [11,22,33,44]
  169. # ret = min(li)
  170. # print(ret)
  171.  
  172. #求一个数字的多少次方
  173. # ret = pow(2,10)
  174. # print(ret)
  175.  
  176. #reversed反转
  177. # a = [11,22,33,44]
  178. # b = reversed(a)
  179. # for i in b:
  180. # print(i)
  181.  
  182. #round 四舍五入
  183. # ret = round(4.8)
  184. # print(ret)
  185.  
  186. #sum求和
  187. # ret = sum((11,22,33,44))
  188. # print(ret)
  189.  
  190. #zip,1 1对应
  191. # li1 = [11,22,33,44,55]
  192. # li2 = [99,88,77,66,89]
  193. # dic = dict(zip(li1,li2))
  194. # print(dic)
  195.  
  196. #sorted 排序
  197. # li = ["1","2sdg;l","57","a","b","A","中国人"]
  198. # lis = sorted(li)
  199. # print(lis)
  200. # for i in lis:
  201. # print(bytes(i,encoding="utf-8"))
  202.  
  203. # #随机生成6位验证码
  204. # import random
  205. # temp = ''
  206. # for i in range(6):
  207. # num = random.randrange(0,4)
  208. # if num ==3 or num ==1:
  209. # rad1 = random.randrange(0,10)
  210. # temp+=str(rad1)
  211. # else:
  212. # rad2 = random.randrange(65,91)
  213. # c1 = chr(rad2)
  214. # temp+=c1
  215. # print(temp)

 

4、文件处理

a、打开文件

  1. name = open('文件路径', '模式')

打开文件时,需要指定文件路径和以何等方式打开文件,打开后,即可获取该文件句柄,日后通过此文件句柄对该文件操作。

打开文件的模式有:

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

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

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

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

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

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

例:

  1. #普通方式打开
  2. # ====pythobnn内部将二进制转换成字符串,通过字符串操作
  3.  
  4. #二进制打开方式
  5. #用户自己操作把字符串转成二进制,然后让电脑识别
  6.  
  7. # 1. 只读模式,r
  8. # a = open("1.log","r") #打开1.log,赋予只读的权限
  9. # ret = a.read() #读取文件
  10. # a.close() #退出文件
  11. # print(ret) #打印文件内容
  12.  
  13. #2.只写模式,w, 如果不存在会创建文件,存在则清空内容
  14. # a = open("3.log","w")
  15. # a.write("sdfhsuigfhuisg")
  16. # a.close()
  17.  
  18. #3.只写模式,x, 如果不存在会创建文件,存在则报错
  19. # a = open("4.log","x")
  20. # a.write("12345678")
  21. # a.close()
  22.  
  23. #4.追加模式,a,不可读,不存在则创建文件,存在则会追加内容
  24. # a = open("4.log","a")
  25. # a.write("asjfioshf")
  26. # a.close()
  27.  
  28. # "b"表示处理二进制文件(如:FTP发送上传ISO镜像文件,linux可忽略,windows处理二进制文件时需标注)
  29.  
  30. #5.只读模式,rb,以字节方式打开,默认打开是字节的方式
  31. # a = open("2.log","rb") #二进制方式读取2.log文件
  32. # date = a.read() #定义变量,读文件
  33. # a.close() #关闭文件
  34. # print(date) #打印文件
  35. # str_data = str(date, encoding="utf-8") #字节转换成utf-8
  36. # print(str_data) # 打印文件
  37.  
  38. #6.只写模式,wb,
  39. # a = open("2.log","wb") #打开文件2.log,可写的模式
  40. # date = "中国人" #定义字符串
  41. # a.write(bytes(date , encoding="utf-8")) #转换成字节,方便计算机识别
  42. # a.close() #关闭文件
  43. # print(date) #打印出来
  44.  
  45. #7.只写模式,xb,
  46. # a = open("6.log","xb")
  47. # date = "张岩林非常帅"
  48. # # a.write("sakfdhisf") #字符串形式会报错,计算机不识别,得转换成字节
  49. # a.write(bytes(date,encoding="utf-8"))
  50. # a.close()
  51. # print(date)
  52.  
  53. #8.追加模式,ab,
  54. # a = open("5.log","ab")
  55. # date = "!张岩林是个帅小伙子"
  56. # a.write(bytes(date,encoding="utf-8"))
  57. # a.close()
  58. # print(date)
  59.  
  60. # #"+"表示具有读写的功能
  61.  
  62. # #9.r+,读写(可读,可写)
  63. # a = open("5.log","r+",encoding="utf-8")
  64. # print(a.tell()) #打开文件后观看指针位置在第几位,默认在起始位置
  65. #
  66. # date = a.read() #第一次读取,指针读取到最后了,(可以加读取的索引位置,3表示只看前三位)
  67. # print(date)
  68. #
  69. # a.write("太帅了") #写的时候会把指针调到最后去写
  70. #
  71. # a.seek(0) #把指针放在第一位进行第二次读取
  72. #
  73. # date = a.read() #第二次读取
  74. # print(date)
  75. # a.close()
  76.  
  77. #10.w+,写读,(可写,可读),先清空内容,在写之后需要把指针放在第一位才能读
  78. # a = open("5.log","w+",encoding="utf-8")
  79. # a.write("张岩林") #清空内容写入“张岩林”
  80. # a.seek(0) #把指针放在第一位
  81. # date = a.read() #进行读取
  82. # a.close() #退出文件
  83. # print(date)
  84.  
  85. #11.x+,写读,(可写,可读),需要创建一个新文件,文件存在会报错,在写之后需要把指针放在第一位才能读
  86. # a = open("7.log","x+",encoding="utf-8")
  87. # a.write("张岩林") #清空内容写入“张岩林”
  88. # a.seek(0) #把指针放在第一位
  89. # date = a.read() #进行读取
  90. # a.close() #退出文件
  91. # print(date)
  92.  
  93. #12.a+,写读,(可写,可读),打开文件的同时,指针已经在最后了
  94. # a = open("5.log","a+",encoding="utf-8")
  95. # date = a.read() #第一次读,没数据,因为指针在最后
  96. # print(date)
  97. #
  98. # a.write("张张") #往最后写入 张
  99. #
  100. # a.seek(0) #把指针放在第一位,让他进行曲读
  101. # date = a.read()
  102. # print(date)
  103. #
  104. # a.close()

  

 

b、操作操作

  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

3.x

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

2.x

  1. a = open("5.log","r+",encoding="utf-8")
  2. # a.truncate() #依赖于指针,截取数据,只剩下指针所在位置的前面的数据
  3. # a.close() #关闭
  4. # a.flush() #强行加入内存
  5. # a.read() #读
  6. # a.readline() #只读取第一行
  7. # a.seek(0) #指针
  8. # a.tell() #当前指针位置
  9. # a.write() #写

  

c、管理上下文

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

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

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

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

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

例:

  1. #关闭文件with
  2. with open("5.log","r") as a:
  3. a.read()
  4.  
  5. #同事打开两个文件,把a复制到b中,读一行写一行,直到写完
  6. with open("5.log","r",encoding="utf-8") as a,open("6.log","w",encoding="utf-8") as b:
  7. for line in a:
  8. b.write(line)

  

lambda表达式

学习条件运算时,对于简单的 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)

 

递归

利用函数编写如下数列:

斐波那契数列指的是这样一个数列 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233,377,610,987,1597,2584,4181,6765,10946,17711,28657,46368...

  1. def func(arg1,arg2):
  2. if arg1 == 0:
  3. print arg1, arg2
  4. arg3 = arg1 + arg2
  5. print arg3
  6. func(arg2, arg3)
  7.  
  8. func(0,1)
  1. def func(n,a,b):
  2. if n == 10:
  3. return a
  4. c = a + b
  5. return func(n+1,b,c)
  6.  
  7. ret = func(1,0,1)
  8. print(ret)
  1. # 列出一组数据
  2. a,b = 0,1
  3. while b <1000:
  4. print(a)
  5. a, b = b, a+ b

  

 

冒泡排序
  1. # li = [11,2,35,14,22,35235,1232141,345,321423,123,123234]
  2. # for j in range(1,len(li)):
  3. # for i in range(len(li)-j):
  4. # if li[i]<li[i+1]:
  5. # temp = li[i]
  6. # li[i]=li[i+1]
  7. # li[i+1]=temp
  8. # print(li)

  

Python Set集合,函数,深入拷贝,浅入拷贝,文件处理的更多相关文章

  1. .net中String是引用类型还是值类型 以及 C#深层拷贝浅层拷贝

    http://www.cnblogs.com/yank/archive/2011/10/24/2204145.html http://www.cnblogs.com/zwq194/archive/20 ...

  2. Python自动化 【第三篇】:Python基础-集合、文件操作、字符编码与转码、函数

    1.        集合 1.1      特性 集合是一个无序的,不重复的数据组合,主要作用如下: 去重,把一个列表变成集合实现自动去重. set可以看成数学意义上的无序和无重复元素的集合,因此,两 ...

  3. 浅入深出之Java集合框架(中)

    Java中的集合框架(中) 由于Java中的集合框架的内容比较多,在这里分为三个部分介绍Java的集合框架,内容是从浅到深,如果已经有java基础的小伙伴可以直接跳到<浅入深出之Java集合框架 ...

  4. 浅入深出之Java集合框架(上)

    Java中的集合框架(上) 由于Java中的集合框架的内容比较多,在这里分为三个部分介绍Java的集合框架,内容是从浅到深,如果已经有java基础的小伙伴可以直接跳到<浅入深出之Java集合框架 ...

  5. 浅入深出之Java集合框架(下)

    Java中的集合框架(下) 由于Java中的集合框架的内容比较多,在这里分为三个部分介绍Java的集合框架,内容是从浅到深,哈哈这篇其实也还是基础,惊不惊喜意不意外 ̄▽ ̄ 写文真的好累,懒得写了.. ...

  6. 跟着ALEX 学python day3集合 文件操作 函数和函数式编程 内置函数

    声明 : 文档内容学习于 http://www.cnblogs.com/xiaozhiqi/  一. 集合 集合是一个无序的,不重复的数据组合,主要作用如下 1.去重 把一个列表变成集合 ,就自动去重 ...

  7. day07 python列表 集合 深浅拷贝

    day07 python   一.知识点补充     1."".join() s = "".join(('1','2','3','4','5'))  #将字符串 ...

  8. 【Python之路】第四篇--Python基础之函数

    三元运算 三元运算(三目运算),是对简单的条件语句的缩写 # 书写格式 result = 值1 if 条件 else 值2 # 如果条件成立,那么将 “值1” 赋值给result变量,否则,将“值2” ...

  9. 『浅入深出』MySQL 中事务的实现

    在关系型数据库中,事务的重要性不言而喻,只要对数据库稍有了解的人都知道事务具有 ACID 四个基本属性,而我们不知道的可能就是数据库是如何实现这四个属性的:在这篇文章中,我们将对事务的实现进行分析,尝 ...

随机推荐

  1. Python学习笔记总结(二)函数和模块

    一.函数 函数的作用:可以计算出一个返回值,最大化代码重用,最小化代码冗余,流程的分解. 1.函数相关的语句和表达式 语句        例子 Calls        myfunc(‘diege', ...

  2. Cmake Error: your compiler "cl" was not Found .etc

    又是环境变量路径等问题,烦死人了. TIPS:请注意,控制台的窗口也有自己的环境变量,从系统环境变量和用户环境变量继承过来的,一个窗口(控制台)可以添加属于自己的环境变量(跟别的控制台窗口没关系) 解 ...

  3. BZOJ1270: [BeijingWc2008]雷涛的小猫

    1270: [BeijingWc2008]雷涛的小猫 Time Limit: 50 Sec  Memory Limit: 162 MBSubmit: 836  Solved: 392[Submit][ ...

  4. 价格更低、SLA 更强的全新 Azure SQL 数据库服务等级将于 9 月正式发布

    继上周公告之后,很高兴向大家宣布更多好消息,作为我们更广泛的数据平台的一部分, 我们将在 Azure 上提供丰富的在线数据服务.9 月,我们将针对 Azure SQL 数据库推出新的服务等级.Azur ...

  5. Android Toast简介

    Toast是Android中一种提供给用户简短信息的视图,该视图已浮于应用程序之上的形式呈现给用户.因为它并不获得焦点,即使用户正在输入什么也不会受到影响.它的目标是尽可能以不显眼的方式,使用户看到你 ...

  6. (一)一个简单的Web服务器

    万丈高楼平地起,首先我们必须了解 超文本传输协议(HTTP) 以后才能够比较清晰的明白web服务器是怎么回事. 1. 浅析Http协议 HTTP是一种协议,允许web服务器和浏览器通过互联网进行来发送 ...

  7. Codeforce 220 div2

    D 插入: 在当前指针位置sz处插入一个1,col[sz]记录插入的内容,sz++; 删除i: 找到第i个1的位置,赋为0; 于是转化为一个维护区间和的问题; trick: 如果是依次删除a[0],a ...

  8. Squid--hash代码分析

    #ifndef SQUID_HASH_H #define SQUID_HASH_H //几个函数和变量的别名 typedef void HASHFREE(void *); typedef int HA ...

  9. Oracle的sql语句中case关键字的用法 & 单双引号的使用

    关于sql中单引号和双引号的使用,来一点说明: 1. 查询列的别名如果含有汉字或者特殊字符(如以'_'开头),需要用双引号引起来.而且只能用双引号,单引号是不可以的. 2. 如果想让某列返回固定的值, ...

  10. java遍历Hashmap/Hashtable的几种方法

    一>java遍历Hashtabe: import java.util.Hashtable; import java.util.Set; public class HashTableTest { ...