PYDay6- 内置函数、验证码、文件操作、发送邮件函数
1、内置函数
1.1Python的内置函数
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)
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 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
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 smtplib
- from email.mime.text import MIMEText
- from email.utils import formataddr
- ret = True
- try:
- 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 = False
- return ret
- i1 = email()
- print(i1)
发送邮件示例
PYDay6- 内置函数、验证码、文件操作、发送邮件函数的更多相关文章
- python基础(5)---整型、字符串、列表、元组、字典内置方法和文件操作介绍
对于python而言,一切事物都是对象,对象是基于类创建的,对象继承了类的属性,方法等特性 1.int 首先,我们来查看下int包含了哪些函数 # python3.x dir(int) # ['__a ...
- python笔记2小数据池,深浅copy,文件操作及函数初级
小数据池就是在内存中已经开辟了一些特定的数据,经一些变量名直接指向这个内存,多个变量间公用一个内存的数据. int: -5 ~ 256 范围之内 str: 满足一定得规则的字符串. 小数据池: 1,节 ...
- 【Unity Shaders】使用CgInclude让你的Shader模块化——Unity内置的CgInclude文件
本系列主要參考<Unity Shaders and Effects Cookbook>一书(感谢原书作者),同一时候会加上一点个人理解或拓展. 这里是本书全部的插图. 这里是本书所需的代码 ...
- php中文件操作常用函数有哪些
php中文件操作常用函数有哪些 一.总结 一句话总结:读写文件函数 判断文件或者目录是否存在函数 创建目录函数 file_exists() mkdir() file_get_content() fil ...
- python 文件操作: 文件操作的函数, 模式及常用操作.
1.文件操作的函数: open("文件名(路径)", mode = '模式', encoding = "字符集") 2.模式: r , w , a , r+ , ...
- python 文件操作的函数
1. 文件操作的函数 open(文件名(路径), mode="?", encoding="字符集") 2. 模式: r, w, a, r+, w+, a+, r ...
- PHP文件操作功能函数大全
PHP文件操作功能函数大全 <?php /* 转换字节大小 */ function transByte($size){ $arr=array("B","KB&quo ...
- php 内置的 html 格式化/美化tidy函数 -- 让你的HTML更美观
php 内置的 html 格式化/美化tidy函数 https://github.com/htacg/tidy-html5 # HTML 格式化 function beautify_html($htm ...
- SpringBoot 常用配置 静态资源访问配置/内置tomcat虚拟文件映射路径
Springboot 再模板引擎中引入Js等文件,出现服务器拒绝访问的错误,需要配置过滤器 静态资源访问配置 @Configuration @EnableWebMvc public class Sta ...
- Python全栈开发之4、内置函数、文件操作和递归
转载请注明出处http://www.cnblogs.com/Wxtrkbc/p/5476760.html 一.内置函数 Python的内置函数有许多,下面的这张图全部列举出来了,然后我会把一些常用的拿 ...
随机推荐
- RTT
Segger RTT的使用 一般arm系统中,如何通过电脑键盘和显示器同mcu进行交互最有效的有两种形式:arm7的semihost,cm时代的traceswo.现在jlink推出了颇具特色的rtt( ...
- c#中的特性
c#中的特性 特性在我的理解就是在类或者方法或者参数上加上指定的标记,然后实现指定的效果. 和Java中的注解@Annotation类似. c#内置的特性之Obsolete [Obsolete(&qu ...
- AJPFX关于延迟加载的单例模式的安全问题解决
请写一个延迟加载的单例模式?写懒汉式:当出现多线程访问时怎么解决?加同步,解决安全问题:效率高吗?不高:怎样解决?通过双重判断的形式解决.懒汉式:延迟加载方式.当多线程访问懒汉式时,因为懒汉式的方法内 ...
- CF1081C Colorful Bricks
思路: dp[i][j]表示到第i个砖块为止共计有j个砖块和它左边的砖块颜色不同. 实现: #include <bits/stdc++.h> using namespace std; ty ...
- PaaS优点与限制(3)
PaaS优点与限制(3) PaaS学习笔记目录 PaaS基础学习(1) 在PaaS上开发Web.移动应用(2) PaaS优点与限制(3) 13. PaaS的核心服务 核心服务是指提供数据存储.SQl. ...
- 明白这十个故事-->你也就参悟了人生 .
1.断箭 不相信自己的意志,永远也做不成将军. 春秋战国时代,一位父亲和他的儿子出征打仗.父亲已做了将军,儿子还只是马前卒.又一阵号角吹响,战鼓雷鸣了,父亲庄严地托起一个箭囊,其中插着一只箭.父亲郑 ...
- LR中webservice服务测试的脚本
Action(){ /* 测试QQ是否在线的功能接口 输入参数:QQ号码 String,默认QQ号码:8698053. 返回数据:String,Y = 在线:N = 离线:E = QQ号码错误:A = ...
- JNI工程搭建及编译
JNI工程搭建及编译 建立Java工程 在具有C/C++比编译器的Eclipse中进行工程的创建,先创建一个简单的Java project,选项和一般同,这里仅仅需要将要调用的C/C++函数声明为na ...
- 单调栈2 POJ3250 类似校内选拔I题
这个题再次证明了单调栈的力量 简单 单调栈 类似上次校内选拔消砖块 一堆牛面朝右排 给出从左到右的 问每个牛的能看到前面牛发型的个数之和 //re原因 因为在执行pop的时候没有判断empty 程序崩 ...
- mysql 外键关联
mysql 外键关联 什么是外键:外键是一个特殊的索引,用于关联两个表,只能是指定内容. 如我将新建一个daka的表,然后将此表的class_id 与另外一个class的表的cid字段关联 class ...