python基础(内置函数+文件操作+lambda)
一、内置函数
注:查看详细猛击这里
常用内置函数代码说明:
# abs绝对值
# i = abs(-123)
# print(i) #返回123,绝对值 # #all,循环参数,如果每个元素为真,那么all返回的为真,有一个为假返回的就是假的
# a = all((None,123,456,False))
# print(a) #返回的为假的,证明中间有False值
#
# #所有的假值有
# #0,None,空值
# # #any 只要之前有一个是真的,返回的就是真
# b = any([11,False])
# print(b) #ascii,去指定对象的类中找__repr__,获取返回值
# #ascii函数
# class Foo:
# def __repr__(self):
# return "tina"
# obj =Foo()
# r = ascii(obj)
# print(r) # 布尔值返回真或假
# print(bool(1))
# print(bool(0)) # #bin二进制
# r = bin(123)
# print(r) # #oct八进制
# r = oct(123)
# print(r) # #int十进制
# r = int(123)
# print(r) # #hex十六进制
# r = hex(123)
# print(r) # #二进制转十进制
# i= int("0b11",base=2)
# print(i) # #八进制转十进制
# i= int("11",base=8)
# print(i) # #十六进制转十进制
# i = int("0xe",base=16)
# print(i)
# bin oct 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)) # #数字代表字母
# c = chr(66)chr()输入数字,找到ascii码对应的字母
# print(c) # #字母代表数字
# c = ord("a")
# print(c) #bytes, 字节
#字节和字符串的转换
# a = bytes("tina",encoding="utf-8")
# print(a)
#bytearray 字节列表 #chr(),把数字转换成字母,只适用于ascii码
# a = chr(65)
# print(a) #ord(),把字母转换成数字,只适用于ascii码
# a = ord("a")
# print(a) #callable表示一个对象是否可执行
# def f1(): #看这个函数能不能执行,能则返回True
# return 123
# f1()
# r = callable(f1)
# print(r) #dir,查看一个类里面存在的功能
# li = []
# print(dir(li))
# help(list) #divmod(),#分页的时候使用
# a = 10/3
# r = divmod(10,3)
# print(r) #compile编译, 把字符串转移成python可执行的代码,知道就行 #eval(),简单的表达式,可以给算出来
# b = eval("a + 69" , {"a":99}) #a可以通过字典声明变量去写入
# print(b) #exec,不会返回值,直接输出结果
# exec("for i in range(10):print(i)") # filter对于序列中的元素进行筛选,最终获取符合条件的序列(需要循环)
# def f1(x):
# if x >22:
# return True
# else:
# return False
#
# ret = filter(f1,[11,22,33,44,55])
# for i in ret:
# print(i) # ret = filter(lambda x: x > 22, [11, 22, 33, 44, 55, 66, 77])
# for i in ret:
# print(i) #map(函数,可以迭代的对象,让元素统一操作)
# def f1(x):
# return x+123
#
# # li = [11,22,33,44,55,66]
# # ret = map(f1,li)
# print(ret)
# for i in ret:
# print(i)
#
# ret = map(lambda x: x + 100 if x%2==1 else x, [11, 22, 33, 44])
# print(ret)
# for i in ret:
# print(i) #globals()获取当前所有的全局变量 #locals()获取当前所有的局部变量
# ret = "asziusdhf"
# def fu1():
# name = 123
# print(locals())
# print(globals())
#
# fu1() #hash 对key的优化,相当于给输出一种哈希值
# li = "sdglgmdgongoaerngonaeorgnienrg"
# print(hash(li)) #isinstance()判断是不是一个类型
# li = [11,22]
# ret = isinstance(li,list)
# print(ret)
############小案例#######################
def obj_len(a):
if isinstance(a,str) or isinstance(a,list) or isinstance(a,tuple):
if len(a)>5:
return True
else:
return False
return None
t = [111,22,2,2,]
tt = obj_len(t)
print(tt)
#iter创建一个可以被迭代的元素
# obj = iter([11,22,33,44])
# print(obj)
# #next,取下一个值,一个变量里的值可以一直往下取,直到没有就报错
# ret = next(obj) #max()取最大的值
# li = [11,22,33,44]
# ret = max(li)
# print(ret) #min()取最小值
# li = [11,22,33,44]
# ret = min(li)
# print(ret) #求一个数字的多少次方
# ret = pow(2,10)
# print(ret) #reversed反转
# a = [11,22,33,44]
# b = reversed(a)
# for i in b:
# print(i) #round 四舍五入
# ret = round(4.8)
# print(ret) #sum求和
# ret = sum((11,22,33,44))
# print(ret) #zip,1 1对应
# li1 = [11,22,33,44,55]
# li2 = [99,88,77,66,89]
# dic = dict(zip(li1,li2))
# print(dic) #sorted 排序
# li = ["1","2sdg;l","57","a","b","A","中国人"]
# lis = sorted(li)
# print(lis)
# for i in lis:
# print(bytes(i,encoding="utf-8"))
######################小案例:############################
# #随机生成6位验证码
# import random
# temp = ''
# for i in range(6):
# num = random.randrange(0,4)
# if num ==3 or num ==1:
# rad1 = random.randrange(0,10)
# temp+=str(rad1)
# else:
# rad2 = random.randrange(65,91)
# c1 = chr(rad2)
# temp+=c1
# print(temp)
二、文件处理
1、打开文件
文件句柄 = open('文件路径', '模式')
打开文件时,需要指定文件路径和以何等方式打开文件,打开后,即可获取该文件句柄,日后通过此文件句柄对该文件操作。
打开文件的模式有:
- r ,只读模式【默认】
- w,只写模式【不可读;不存在则创建;存在则清空内容;】
- x, 只写模式【不可读;不存在则创建,存在则报错】
- a, 追加模式【不可读; 不存在则创建;存在则只追加内容;】
"+" 表示可以同时读写某个文件
- r+, 读写【可读,可写】
- w+,写读【可读,可写】
- x+ ,写读【可读,可写】
- a+, 写读【可读,可写】
"b"表示以字节的方式操作
- rb 或 r+b
- wb 或 w+b
- xb 或 w+b
- ab 或 a+b
注:以b方式打开时,读取到的内容是字节类型,写入时也需要提供字节类型
#普通方式打开
# ====python内部将二进制转换成字符串,通过字符串操作 #二进制打开方式
#用户自己操作把字符串转成二进制,然后让电脑识别 # 1. 只读模式,r
# a = open("1.log","r") #打开1.log,赋予只读的权限
# ret = a.read() #读取文件
# a.close() #退出文件
# print(ret) #打印文件内容 #2.只写模式,w, 如果不存在会创建文件,存在则清空内容
# a = open("3.log","w")
# a.write("sdfhsuigfhuisg")
# a.close() #3.只写模式,x, 如果不存在会创建文件,存在则报错
# a = open("4.log","x")
# a.write("12345678")
# a.close() #4.追加模式,a,不可读,不存在则创建文件,存在则会追加内容
# a = open("4.log","a")
# a.write("asjfioshf")
# a.close() # "b"表示处理二进制文件(如:FTP发送上传ISO镜像文件,linux可忽略,windows处理二进制文件时需标注) #5.只读模式,rb,以字节方式打开,默认打开是字节的方式
# a = open("2.log","rb") #二进制方式读取2.log文件
# date = a.read() #定义变量,读文件
# a.close() #关闭文件
# print(date) #打印文件
# str_data = str(date, encoding="utf-8") #字节转换成utf-8
# print(str_data) # 打印文件 #6.只写模式,wb,
# a = open("2.log","wb") #打开文件2.log,可写的模式
# date = "中国人" #定义字符串
# a.write(bytes(date , encoding="utf-8")) #转换成字节,方便计算机识别
# a.close() #关闭文件
# print(date) #打印出来 #7.只写模式,xb,
# a = open("6.log","xb")
# date = "哈哈哈"
# # a.write("sakfdhisf") #字符串形式会报错,计算机不识别,得转换成字节
# a.write(bytes(date,encoding="utf-8"))
# a.close()
# print(date) #8.追加模式,ab,
# a = open("5.log","ab")
# date = "呵呵呵"
# a.write(bytes(date,encoding="utf-8"))
# a.close()
# print(date) # #"+"表示具有读写的功能 # #9.r+,读写(可读,可写)
# a = open("5.log","r+",encoding="utf-8")
# print(a.tell()) #打开文件后观看指针位置在第几位,默认在起始位置
#
# date = a.read() #第一次读取,指针读取到最后了,(可以加读取的索引位置,3表示只看前三位)
# print(date)
#
# a.write("嘿嘿嘿") #写的时候会把指针调到最后去写
#
# a.seek(0) #把指针放在第一位进行第二次读取
#
# date = a.read() #第二次读取
# print(date)
# a.close()
#10.w+,写读,(可写,可读),先清空内容,在写之后需要把指针放在第一位才能读
# a = open("5.log","w+",encoding="utf-8")
# a.write("哦哦") #清空内容写入“哦哦”
# a.seek(0) #把指针放在第一位
# date = a.read() #进行读取
# a.close() #退出文件
# print(date) #11.x+,写读,(可写,可读),需要创建一个新文件,文件存在会报错,在写之后需要把指针放在第一位才能读
# a = open("7.log","x+",encoding="utf-8")
# a.write("嘻嘻嘻") #清空内容写入“嘻嘻嘻”
# a.seek(0) #把指针放在第一位
# date = a.read() #进行读取
# a.close() #退出文件
# print(date) #12.a+,写读,(可写,可读),打开文件的同时,指针已经在最后了
# a = open("5.log","a+",encoding="utf-8")
# date = a.read() #第一次读,没数据,因为指针在最后
# print(date)
#
# a.write("嗯嗯") #往最后写入 嗯嗯
#
# a.seek(0) #把指针放在第一位,让他进行曲读
# date = a.read()
# print(date)
#
# a.close()
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
3.0
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
2.0
a = open("5.log","r+",encoding="utf-8")
# a.truncate() #依赖于指针,截取数据,只剩下指针所在位置的前面的数据
# a.close() #关闭
# a.flush() #强行加入内存
# a.read() #读
# a.readline() #只读取第一行
# a.seek(0) #指针
# a.tell() #当前指针位置
# a.write() #写
3、文件上下文管理
为了避免打开文件后忘记关闭,可以通过管理上下文,即:
1
2
3
|
with open ( 'log' , 'r' ) as f: ... |
如此方式,当with代码块执行完毕时,内部会自动关闭并释放文件资源。
在Python 2.7 及以后,with又支持同时对多个文件的上下文进行管理,即:
1
2
|
with open ( 'log1' ) as obj1, open ( 'log2' ) as obj2: pass |
例:
1
2
3
4
5
6
7
8
|
#关闭文件with with open ( "5.log" , "r" ) as a: a.read() #同事打开两个文件,把a复制到b中,读一行写一行,直到写完 with open ( "5.log" , "r" ,encoding = "utf-8" ) as a, open ( "6.log" , "w" ,encoding = "utf-8" ) as b: for line in a: b.write(line) |
三、lambda表达式
学习条件运算时,对于简单的 if else 语句,可以使用三元运算来表示,即:
1
2
3
4
5
6
7
8
|
# 普通条件语句 if 1 = = 1 : name = 'wupeiqi' else : name = 'alex' # 三元运算 name = 'wupeiqi' if 1 = = 1 else 'alex' |
对于简单的函数,也存在一种简便的表示方式,即:lambda表达式
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
# ###################### 普通函数 ###################### # 定义函数(普通方式) def func(arg): return arg + 1 # 执行函数 result = func( 123 ) # ###################### lambda ###################### # 定义函数(lambda表达式) my_lambda = lambda arg : arg + 1 # 执行函数 result = my_lambda( 123 ) |
python基础(内置函数+文件操作+lambda)的更多相关文章
- python基础——内置函数
python基础--内置函数 一.内置函数(python3.x) 内置参数详解官方文档: https://docs.python.org/3/library/functions.html?highl ...
- python基础-内置函数详解
一.内置函数(python3.x) 内置参数详解官方文档: https://docs.python.org/3/library/functions.html?highlight=built#ascii ...
- python基础--内置函数map
num_1=[1,2,10,5,3,7] # num_2=[] # for i in num_1: # num_2.append(i**2) # print(num_2) # def map_test ...
- 第三天 函数 三元运算 lambda表达式 内置函数 文件操作
面向过程: 直接一行一行写代码,遇到重复的内容复制黏贴. 不利于代码阅读 代码没有复用 面向对象 将代码块定义为函数,以后直接调用函数 增强了复用性 函数的定义方法 def 函数名(传递参数): 函数 ...
- python匿名函数 高阶函数 内置函数 文件操作
1.匿名函数 匿名就是没有名字 def func(x,y,z=1): return x+y+z 匿名 lambda x,y,z=1:x+y+z #与函数有相同的作用域,但是匿名意味着引用计数为0,使用 ...
- python基础----内置函数----匿名函数(lambda)
Python3版本所有的内置函数: 1. abs() 获取绝对值 >>> abs(-) >>> abs() >>> abs() >>& ...
- Python 基础 内置函数 迭代器与生成器
今天就来介绍一下内置函数和迭代器 .生成器相关的知识 一.内置函数:就是Python为我们提供的直接可以使用的函数. 简单介绍几个自己认为比较重要的 1.#1.eval函数:(可以把文件中每行中的数据 ...
- Python基础-内置函数、模块、函数、json
内置函数 1.id()返回对象的内存地址: 2. type() 返回对象类型: 3.print()打印输出: 4. input()接受一个标准输入数据,返回为string类型: 5. list() ...
- Python菜鸟之路:Python基础-内置函数补充
常用内置函数及用法: 1. callable() def callable(i_e_, some_kind_of_function): # real signature unknown; restor ...
随机推荐
- document.body.scrollTop or document.documentElement.scrollTop
用Javascript获取DOM节点相对于页面的绝对坐标时,需要计算当前页面的滚动距离,而这个值的获取又取决于浏览器. 在Firefox或Chrome浏览器的控制台可以查看document.bod ...
- html只允许输入的数据校验,只允许输入字母汉字数字等
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...
- dede数据库类使用方法 $dsql
dedecms的数据库操作类,非常实用,在二次开发中尤其重要,这个数据库操作类说明算是奉献给大家的小礼物了. 引入common.inc.php文件 require_once (dirname(__FI ...
- JavaScript 进阶教程一 JavaScript 中的事件流 - 事件冒泡和事件捕获
先看下面的示例代码: <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Jav ...
- P1311 选择客栈
开始写了一个O(n3)的算法,只得了60,后来思考(找题解),得到了一个O(nk)的算法 其实就是一种预处理的思想,对于每一个客栈而言,只要我们预处理出他前面可以匹配的客栈数量,就可以了. 所以我们记 ...
- maketrans translate
1. makestrans()用法 语法: str.maketrans(intab, outtab]); Python maketrans() 方法用于创建字符映射的转换表,对于接受两个参数的最简单的 ...
- C# Winform 界面中各控件随着窗口大小变化
在做一项工程中,由于不确定目标平台的分辨率,而正常使用要求铺满整个屏幕,所以界面中的各个控件必须能够适应窗口的变化. 首先想到的就是控件的百分比布局,但是再尝试写了几个控件的Location和Size ...
- oracle创建、删除账户
1.创建 /*第1步:创建表空间 */create tablespace xybi datafile 'E:\oracle\oradata\zzxe\xybi_d01' size 100M ; /*第 ...
- Talend 从Excel导入Saleforce数据(一) 直接从salesforce lookup 性能的噩梦
速度的瓶颈是在查询Sales force是否有该电话号码的联系人资料. TMap属性的 lookup Model, 如果用Load Once, 则会把SaleForce的contact全部load下来 ...
- composer--------------今天遇到几个奇葩问题,记录一下
1.就是composer跟xdebug有冲突,每次用composer命令的时候都要报xdebug的错误,其实这个只要你去php的配置文件里面将xdebug注释掉就可以了,但是我注释掉了以后还是不行.找 ...