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、随机验证码函数:

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

View Code

3、文件操作

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

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

3.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 文件操作的方法

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

View Code

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 文件操作示例代码

#!/usr/bin/env python
# -*- coding:utf-8 -*-####基本操作方法
#默认是只读模式,默认编码方式:utf-8
# f = open('ha.log')
# data = f.read()
# f.close()
# print(data)
#只读,r
# f = open("ha.log","r")
# f.write("asdfs")
# f.close()
#只写,w  ---存在就清空,打开就清空
# f = open("ha1.log","w")
# f.write("Hello world!")
# f.close()
#只写 ,x
# f = open("ha2.log","x")
# f.write("Hello world1!")
# f.close()
#追加  a,不可读
# f = open("ha2.log","a")
# f.write("\nHello world! a mode")
# f.close()### 字节的方式打开
## 默认读取到的都是字节,不用设置编码方式
## 1、 只读,rb
# f = open("ha.log","rb")
# data =f.read()
# f.close()
# print(type(data))
# print(data)
# print(str(data,encoding="utf-8"))#2 只写,wb
# f = open("ha.log","wb")
# f.write(bytes("中国",encoding="utf-8"))
# f.close()### r+ ,w+,x+,a+#r+
# f = open("ha.log",'r+',encoding="utf-8")
# print(f.tell())
# data = f.read()
# print(type(data),data)
# f.write("德国人")
# print(f.tell())
# data = f.read()
# f.close()#w+  先清空,之后写入的可读,写后指针到最后
# f = open("ha.log","w+",encoding="utf-8")
# f.write("何莉莉")
# f.seek(0)  # 指针调到最后
# data = f.read()
# f.close()
# print(data)#  x+  功能类似w+,区别:若文件存在即报错#a +    打开的同时指针到最后
f = open("ha.log","a+",encoding="utf-8")
print(f.tell())
f.write("SB")
print(f.tell())
data = f.read()
print(data)
f.seek(0)
data = f.read()
print(data)
print(type(data))
print(type(f))
f.close()

文件操作示例

4、lambda表达式

  f1 = lambda x,y: 9+x

5、发送邮件实例代码

#!/usr/bin/env python
# -*- coding:utf-8 -*-
def email():import smtplibfrom email.mime.text import MIMETextfrom email.utils import formataddrret = Truetry: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')msg['From'] = formataddr(["b2b", 'john@xxx.com'])msg['To'] = formataddr(["hi hi hi  ", 'john2@xxx.com'])msg['Subject'] = "主题2017年5月23日"server = smtplib.SMTP("mail.xxx.com", 25)server.login("john1", "txxx0517")server.sendmail('john1@tasly.com', ['john2@tasly.com', ], msg.as_string())server.quit()except:ret = Falsereturn  ret
i1 =  email()
print(i1)

发送邮件示例

转载于:https://www.cnblogs.com/workherd/p/6358672.html

PYDay6- 内置函数、验证码、文件操作、发送邮件函数相关推荐

  1. php内置邮件sendmail发送,PHP发送邮件函数sendmail()

    不需要邮件服务器,不使用mail内置函数,一个类就搞定,利用PHPMailer类我写了一个自定义函数 sendmail() ,VERY实用! 以前也在几个PHP论坛上发表过这个发邮件的函数,今天再发, ...

  2. Python内置十大文件操作

    日常对于批量处理文件的需求非常多,经常需要用Python写脚本调用外部文件! 本次整理Python中最常用的十大文件操作方法,直接拿来用就行啦! 01 创建和打开文件 想要操作文件需要先创建或代开指定 ...

  3. python将元祖设为整形_python基础(5)---整型、字符串、列表、元组、字典内置方法和文件操作介绍...

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

  4. python 文件函数_python文件操作及函数学习

    文件操作 文件读 f = open('a.txt', encoding='utf-8', mode='r')  #只读方式打开文件 data = f.read()  #read函数读取所有文件内容,光 ...

  5. C++文件操作API函数介绍

    转自 http://www.studentblog.net/m/tonycat/archives/2006/26364.html 文件的基本概念 所谓"文件"是指一组相关数据的有序 ...

  6. Python开发【第三篇】:文件操作与函数

    内容概要 文件操作 初始函数 函数定义与调用 函数的返回值 函数的参数 函数进阶 函数参数--动态传参 名称空间 作用域 函数的嵌套 函数名的运用 gloabal,nonlocal 关键字 1.文件操 ...

  7. python 集合、函数、文件操作

    集合 一.集合的特性 无序,不重复 二.集合的创建方法 1. 大括号 >>> s = {11, 22, 33, 11} >>> s {33, 11, 22} 2.初 ...

  8. 爬虫(21)crawlspider讲解古诗文案例补充+小程序社区案例+汽车之家案例+scrapy内置的下载文件的方法

    文章目录 第十九章 crawlspider讲解 1. 古诗文案例crawlspider 1.1 需求 1.2 处理 1.3 解析 2. 小程序社区案例 2.1 创建项目 2.2 项目配置 2.3 解析 ...

  9. 04-前端技术_ javaScript内置对象与DOM操作

    目录 五,javaScript内置对象与DOM操作 1,JavaScript对象定义和使用 2,JavaScript内置对象 2.1 Array数组 2.1.1 创建方式 2.1.2 常用属性: 2. ...

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

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

最新文章

  1. 设置RabbitMQ远程ip登录
  2. 华南赛区线上比赛安排
  3. 一文带你深入拆解Java虚拟机
  4. 微信小程序图片上传(文字识别)
  5. luabind-0.9.1在windows、linux下的使用详解及示例
  6. PHPCMS的产品筛选功能
  7. STL_set/vector/deque
  8. 使用spring 配置数据源,并用数据源得到连接,操作sql
  9. 干货 物联网卡使用9大常见问题解惑
  10. layui修改头像功能
  11. 视频教程-Visio应用视频教程(上)-Office/WPS
  12. 斯伦贝谢好进吗_拼集市 环球购30%智商税你还交吗
  13. 【开源】Java身份证号码识别系统
  14. 爬取站大爷的免费ip代理
  15. MapReduce中各个阶段的分析(转自道法—自然老师)
  16. 【应急响应】黑客入侵应急分析手工排查
  17. 2020h黑苹果 y7000p_拯救者Y7000黑苹果升级macOS 10.15.4分享
  18. 狂神JavaWeb课程笔记
  19. layui 的简单使用
  20. PC装苹果系统(详解)

热门文章

  1. Android之利用ColorMatrix进行图片的各种特效处理
  2. Android OkHttp之 offline cache
  3. Postman--Pre-request执行其他接口
  4. sixth week:third work
  5. global 和 nonlocal关键字
  6. 邪恶改装2:用单片机实现一次简单的wifi密码欺骗
  7. 模板引擎(smarty)知识点总结II
  8. android 绘图之Canvas,Paint类
  9. 关于Unity -Vuforia -Android 开发 ,平台的搭建(极品菜鸟完整版)
  10. centos 6.3 安装reids