1、内置函数

1.1Python的内置函数

abs() dict() help() min() setattr()
all() dir() hex() next() slice()
any() divmod() id() object() sorted()
ascii() enumerate() input() oct() staticmethod()
bin() eval() int() open() str()
bool() exec() isinstance() ord() sum()
bytearray() filter() issubclass() pow() super()
bytes() float() iter() print() tuple()
callable() format() len() property() type()
chr() frozenset() list() range() vars()
classmethod() getattr() locals() repr() zip()
compile() globals() map() reversed() __import__()
complex() hasattr() max() round()  
delattr() hash() memoryview() set()

1.2一阶段需要掌握的函数

2、随机验证码函数:

  1. import random
  2. #assii:大写字母:65~90,小写 97~122 数字48-57
  3. tmp = ""
  4. for i in range(6):
  5. num =random.randrange(1,4)
  6. if num == 1:
  7. rad2 = random.randrange(0,10)
  8. tmp = tmp+str(rad2)
  9. elif num == 2:
  10. rad3 = random.randrange(97, 123)
  11. tmp = tmp + chr(rad3)
  12. else:
  13. rad1 = random.randrange(65,91)
  14. c = chr(rad1)
  15. tmp = tmp + c
  16. print(tmp)

3、文件操作

使用open函数操作,该函数用于文件处理。

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

3.1打开文件

  1. open(文件名,模式,编码)
    eg
    f = open("ha.log","a+",encoding="utf-8")
    注:默认打开模式r

3.2打开模式:

  基本模式:  

• r:只读模式(不可写)
• w:只写模式(不可读,不存在则创建,存在则清空内容(只要打开就清空))
• x:只写模式(不可读,不存在则创建,存在则报错)
• a:追加模式(不可读,不存在就创建,存在只追加内容)

  二进制模式:rb\wb\xb\ab

    特点:二进制打开,对文件的操作都需以二进制的方式进行操作

  对文件进行读写    

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

3.3 文件操作的方法

  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

3.4 管理上下文

使用open方法打开后要关闭文本。

with方法后,python会自动回收资源

py2.7以后的版本with方法支持同时对两个文件进行操作

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

3.5 文件日常操作

open(文件名,模式,编码)
close()
flush():将内存中的文件数据写入磁盘
read():读取指针的内容
readline():只都一行内容
seek()定位指针位置
tell()获取当前指针位置
truncate() 截断数据,仅保留指定之前的数据,依赖于指针
write() 写入数据

3.6 文件操作示例代码

  1. #!/usr/bin/env python
  2. # -*- coding:utf-8 -*-
  3.  
  4. ####基本操作方法
  5. #默认是只读模式,默认编码方式:utf-8
  6. # f = open('ha.log')
  7. # data = f.read()
  8. # f.close()
  9. # print(data)
  10. #只读,r
  11. # f = open("ha.log","r")
  12. # f.write("asdfs")
  13. # f.close()
  14. #只写,w ---存在就清空,打开就清空
  15. # f = open("ha1.log","w")
  16. # f.write("Hello world!")
  17. # f.close()
  18. #只写 ,x
  19. # f = open("ha2.log","x")
  20. # f.write("Hello world1!")
  21. # f.close()
  22. #追加 a,不可读
  23. # f = open("ha2.log","a")
  24. # f.write("\nHello world! a mode")
  25. # f.close()
  26.  
  27. ### 字节的方式打开
  28. ## 默认读取到的都是字节,不用设置编码方式
  29. ## 1、 只读,rb
  30. # f = open("ha.log","rb")
  31. # data =f.read()
  32. # f.close()
  33. # print(type(data))
  34. # print(data)
  35. # print(str(data,encoding="utf-8"))
  36.  
  37. #2 只写,wb
  38. # f = open("ha.log","wb")
  39. # f.write(bytes("中国",encoding="utf-8"))
  40. # f.close()
  41.  
  42. ### r+ ,w+,x+,a+
  43.  
  44. #r+
  45. # f = open("ha.log",'r+',encoding="utf-8")
  46. # print(f.tell())
  47. # data = f.read()
  48. # print(type(data),data)
  49. # f.write("德国人")
  50. # print(f.tell())
  51. # data = f.read()
  52. # f.close()
  53.  
  54. #w+ 先清空,之后写入的可读,写后指针到最后
  55. # f = open("ha.log","w+",encoding="utf-8")
  56. # f.write("何莉莉")
  57. # f.seek(0) # 指针调到最后
  58. # data = f.read()
  59. # f.close()
  60. # print(data)
  61.  
  62. # x+ 功能类似w+,区别:若文件存在即报错
  63.  
  64. #a + 打开的同时指针到最后
  65. f = open("ha.log","a+",encoding="utf-8")
  66. print(f.tell())
  67. f.write("SB")
  68. print(f.tell())
  69. data = f.read()
  70. print(data)
  71. f.seek(0)
  72. data = f.read()
  73. print(data)
  74. print(type(data))
  75. print(type(f))
  76. f.close()

文件操作示例

4、lambda表达式

  f1 = lambda x,y: 9+x

5、发送邮件实例代码

  1. #!/usr/bin/env python
  2. # -*- coding:utf-8 -*-
  3. def email():
  4. import smtplib
  5. from email.mime.text import MIMEText
  6. from email.utils import formataddr
  7. ret = True
  8. try:
  9. msg = MIMEText('邮件内容 test mail 2017-5-27 09:16:14 2017年1月27日11:16:37 \n 2017年1月28日06:47:51', 'plain', 'utf-8')
  10. msg['From'] = formataddr(["b2b", 'john@xxx.com'])
  11. msg['To'] = formataddr(["hi hi hi ", 'john2@xxx.com'])
  12. msg['Subject'] = "主题2017年5月23日"
  13.  
  14. server = smtplib.SMTP("mail.xxx.com", 25)
  15. server.login("john1", "txxx0517")
  16. server.sendmail('john1@tasly.com', ['john2@tasly.com', ], msg.as_string())
  17. server.quit()
  18. except:
  19. ret = False
  20. return ret
  21. i1 = email()
  22. print(i1)

发送邮件示例

PYDay6- 内置函数、验证码、文件操作、发送邮件函数的更多相关文章

  1. python基础(5)---整型、字符串、列表、元组、字典内置方法和文件操作介绍

    对于python而言,一切事物都是对象,对象是基于类创建的,对象继承了类的属性,方法等特性 1.int 首先,我们来查看下int包含了哪些函数 # python3.x dir(int) # ['__a ...

  2. python笔记2小数据池,深浅copy,文件操作及函数初级

    小数据池就是在内存中已经开辟了一些特定的数据,经一些变量名直接指向这个内存,多个变量间公用一个内存的数据. int: -5 ~ 256 范围之内 str: 满足一定得规则的字符串. 小数据池: 1,节 ...

  3. 【Unity Shaders】使用CgInclude让你的Shader模块化——Unity内置的CgInclude文件

    本系列主要參考<Unity Shaders and Effects Cookbook>一书(感谢原书作者),同一时候会加上一点个人理解或拓展. 这里是本书全部的插图. 这里是本书所需的代码 ...

  4. php中文件操作常用函数有哪些

    php中文件操作常用函数有哪些 一.总结 一句话总结:读写文件函数 判断文件或者目录是否存在函数 创建目录函数 file_exists() mkdir() file_get_content() fil ...

  5. python 文件操作: 文件操作的函数, 模式及常用操作.

    1.文件操作的函数: open("文件名(路径)", mode = '模式', encoding = "字符集") 2.模式: r , w , a , r+ , ...

  6. python 文件操作的函数

    1. 文件操作的函数 open(文件名(路径), mode="?", encoding="字符集") 2. 模式: r, w, a, r+, w+, a+, r ...

  7. PHP文件操作功能函数大全

    PHP文件操作功能函数大全 <?php /* 转换字节大小 */ function transByte($size){ $arr=array("B","KB&quo ...

  8. php 内置的 html 格式化/美化tidy函数 -- 让你的HTML更美观

    php 内置的 html 格式化/美化tidy函数 https://github.com/htacg/tidy-html5 # HTML 格式化 function beautify_html($htm ...

  9. SpringBoot 常用配置 静态资源访问配置/内置tomcat虚拟文件映射路径

    Springboot 再模板引擎中引入Js等文件,出现服务器拒绝访问的错误,需要配置过滤器 静态资源访问配置 @Configuration @EnableWebMvc public class Sta ...

  10. Python全栈开发之4、内置函数、文件操作和递归

    转载请注明出处http://www.cnblogs.com/Wxtrkbc/p/5476760.html 一.内置函数 Python的内置函数有许多,下面的这张图全部列举出来了,然后我会把一些常用的拿 ...

随机推荐

  1. RTT

    Segger RTT的使用 一般arm系统中,如何通过电脑键盘和显示器同mcu进行交互最有效的有两种形式:arm7的semihost,cm时代的traceswo.现在jlink推出了颇具特色的rtt( ...

  2. c#中的特性

    c#中的特性 特性在我的理解就是在类或者方法或者参数上加上指定的标记,然后实现指定的效果. 和Java中的注解@Annotation类似. c#内置的特性之Obsolete [Obsolete(&qu ...

  3. AJPFX关于延迟加载的单例模式的安全问题解决

    请写一个延迟加载的单例模式?写懒汉式:当出现多线程访问时怎么解决?加同步,解决安全问题:效率高吗?不高:怎样解决?通过双重判断的形式解决.懒汉式:延迟加载方式.当多线程访问懒汉式时,因为懒汉式的方法内 ...

  4. CF1081C Colorful Bricks

    思路: dp[i][j]表示到第i个砖块为止共计有j个砖块和它左边的砖块颜色不同. 实现: #include <bits/stdc++.h> using namespace std; ty ...

  5. PaaS优点与限制(3)

    PaaS优点与限制(3) PaaS学习笔记目录 PaaS基础学习(1) 在PaaS上开发Web.移动应用(2) PaaS优点与限制(3) 13. PaaS的核心服务 核心服务是指提供数据存储.SQl. ...

  6. 明白这十个故事-->你也就参悟了人生 .

    1.断箭 不相信自己的意志,永远也做不成将军.  春秋战国时代,一位父亲和他的儿子出征打仗.父亲已做了将军,儿子还只是马前卒.又一阵号角吹响,战鼓雷鸣了,父亲庄严地托起一个箭囊,其中插着一只箭.父亲郑 ...

  7. LR中webservice服务测试的脚本

    Action(){ /* 测试QQ是否在线的功能接口 输入参数:QQ号码 String,默认QQ号码:8698053. 返回数据:String,Y = 在线:N = 离线:E = QQ号码错误:A = ...

  8. JNI工程搭建及编译

    JNI工程搭建及编译 建立Java工程 在具有C/C++比编译器的Eclipse中进行工程的创建,先创建一个简单的Java project,选项和一般同,这里仅仅需要将要调用的C/C++函数声明为na ...

  9. 单调栈2 POJ3250 类似校内选拔I题

    这个题再次证明了单调栈的力量 简单 单调栈 类似上次校内选拔消砖块 一堆牛面朝右排 给出从左到右的 问每个牛的能看到前面牛发型的个数之和 //re原因 因为在执行pop的时候没有判断empty 程序崩 ...

  10. mysql 外键关联

    mysql 外键关联 什么是外键:外键是一个特殊的索引,用于关联两个表,只能是指定内容. 如我将新建一个daka的表,然后将此表的class_id 与另外一个class的表的cid字段关联 class ...