本章,咱们详细了解下,set集合使用、Python的函数相关功能及使用、open函数功能使用及其余(with,内置函数)功能使用;html
建立集合有两种方式:python
1) 直接建立linux
se = {"jihe",22,"long",18} 或是 se = {"jihe",22,"long",18,18,22} # print(se) 执行结果: {18, 'jihe', 'long', 22}程序员
2)使用set建立express
li = ["jihe",22,"long",18,22,"jihe"] 编程
li = set(li) 或是 li = set(["jihe",22,"long",18,22,"jihe"]) # print(li) 执行结果:{18, 'long', 'jihe', 22} 小程序
惊奇的发现,结果居然相同(虽然位置不一样),这是为何呢?windows
接下来,聊聊集合的特性,一切将迎刃而解。app
经过执行结果,咱们能够看到两种现象:less
1) 执行的结果是无序的,不是按照咱们赋值的顺序排列的;
2) 是不重复的序列, 重复的值,只记录一次;
小结:
1. 集合是{}中包含(不可变类型元素)字符串或数字类型的一个序列; 若是{}有列表、字典,就会报错;元组不会报错,由于它是不可变类型;
2. 集合能够用set()建立,内容包含可迭代的对象;如列表、字符串、元组等,若是是字典,只使用Keys; 数字不能够,由于数字是不可迭代的;
3. 集合是无序的(这点和字典同样),元素不重复,每个元素都是惟一的;
python的set和其余语言相似, 是一个无序不重复元素集, 基本功能包括关系测试和消除重复元素.
集合对象还支持union(联合), intersection(交), difference(差)和sysmmetric difference(对称差集)等数学运算.
下面使用例子介绍说明:
s = set([3,5,9,10]) #建立一个数值集合 t = set("Hello") #建立一个惟一字符的集合 与列表和元组不一样,集合是无序的,也没法经过数字进行索引。此外,集合中的元素不能重复。例如,若是检查前面代码中t集合的值,结果会是: >>> t set(['H', 'e', 'l', 'o']) 注意只出现了一个'l'。 集合支持一系列标准操做,包括并集、交集、差集和对称差集,例如: a = t | s # t 和 s的并集 b = t & s # t 和 s的交集 c = t – s # 求差集(项在t中,但不在s中) d = t ^ s # 对称差集(项在t或s中,但不会同时出如今两者中) 基本操做: t.add('x') # 添加一项 s.update([10,37,42]) # 在s中添加多项 使用remove()能够删除一项: t.remove('H') len(s) set 的长度 x in s 测试 x 是不是 s 的成员 x not in s 测试 x 是否不是 s 的成员 s.issubset(t) s <= t 测试是否 s 中的每个元素都在 t 中 s.issuperset(t) s >= t 测试是否 t 中的每个元素都在 s 中 s.union(t) s | t 返回一个新的 set 包含 s 和 t 中的每个元素 s.intersection(t) s & t 返回一个新的 set 包含 s 和 t 中的公共元素 s.difference(t) s - t 返回一个新的 set 包含 s 中有可是 t 中没有的元素 s.symmetric_difference(t) s ^ t 返回一个新的 set 包含 s 和 t 中不重复的元素 s.copy() 返回 set “s”的一个浅复制 请注意:union(), intersection(), difference() 和 symmetric_difference() 的非运算符(non-operator,就是形如 s.union()这样的)版本将会接受任何 iterable 做为参数。相反,它们的运算符版本(operator based counterparts)要求参数必须是 sets。这样能够避免潜在的错误,如:为了更可读而使用 set('abc') & 'cbs' 来替代 set('abc').intersection('cbs')。从 2.3.1 版本中作的更改:之前全部参数都必须是 sets。 另外,Set 和 ImmutableSet 二者都支持 set 与 set 之间的比较。两个 sets 在也只有在这种状况下是相等的:每个 set 中的元素都是另外一个中的元素(两者互为subset)。一个 set 比另外一个 set 小,只有在第一个 set 是第二个 set 的 subset 时(是一个 subset,可是并不相等)。一个 set 比另外一个 set 打,只有在第一个 set 是第二个 set 的 superset 时(是一个 superset,可是并不相等)。 子 set 和相等比较并不产生完整的排序功能。例如:任意两个 sets 都不相等也不互为子 set,所以如下的运算都会返回 False:a<b, a==b, 或者a>b。所以,sets 不提供 __cmp__ 方法。 由于 sets 只定义了部分排序功能(subset 关系),list.sort() 方法的输出对于 sets 的列表没有定义。 运算符 运算结果 hash(s) 返回 s 的 hash 值 下面这个表列出了对于 Set 可用二对于 ImmutableSet 不可用的运算: 运算符(voperator) 等价于 运算结果 s.update(t) s |= t 返回增长了 set “t”中元素后的 set “s” s.intersection_update(t) s &= t 返回只保留含有 set “t”中元素的 set “s” s.difference_update(t) s -= t 返回删除了 set “t”中含有的元素后的 set “s” s.symmetric_difference_update(t) s ^= t 返回含有 set “t”或者 set “s”中有而不是二者都有的元素的 set “s” s.add(x) 向 set “s”中增长元素 x s.remove(x) 从 set “s”中删除元素 x, 若是不存在则引起 KeyError s.discard(x) 若是在 set “s”中存在元素 x, 则删除 s.pop() 删除而且返回 set “s”中的一个不肯定的元素, 若是为空则引起 KeyError s.clear() 删除 set “s”中的全部元素 请注意:非运算符版本的 update(), intersection_update(), difference_update()和symmetric_difference_update()将会接受任意 iterable 做为参数。从 2.3.1 版本作的更改:之前全部参数都必须是 sets。 还请注意:这个模块还包含一个 union_update() 方法,它是 update() 方法的一个别名。包含这个方法是为了向后兼容。程序员们应该多使用 update() 方法,由于这个方法也被内置的 set() 和 frozenset() 类型支持。
上面例子的内容比较多,着重记如下几个重要功能,知道是干什么就好了,遇到这种判断时,能想到set有这个功能能够实现;
1)difference() 差集 例子:
f0 = set(["seie",22,44,'alex','eric']) f1 = set(["seie",33,22,55,"eric","peiqi"]) f2 = f0.difference(f1) print(f0) print(f1) print(f2) 执行结果: {'alex', 'seie', 44, 22, 'eric'} {33, 'seie', 'peiqi', 55, 22, 'eric'} {'alex', 44}
# 将f0 中和 f1 里不一样的元素取出,差集计算;
2) intersection() 交集,例子:
f0 = set(["seie",22,44,'alex','eric']) f1 = set(["seie",33,22,55,"eric","peiqi"]) f2 = f0.difference(f1) print(f0) print(f1) f3 = f0.intersection(f1) print(f3) 执行结果: {'eric', 44, 'seie', 22, 'alex'} {33, 'seie', 'peiqi', 22, 55, 'eric'} {'eric', 'seie', 22}
# 将f0 中和 f1 里相同的元素取出,交集计算;
3)symmetric_difference() 两个集合的并集减交集,例子:
f0 = set(["seie",22,44,'alex','eric']) f1 = set(["seie",33,22,55,"eric","peiqi"]) print(f0) print(f1) f4 = f0.symmetric_difference(f1) print(f4) 执行结果: {'alex', 44, 'eric', 22, 'seie'} {33, 'seie', 22, 55, 'peiqi', 'eric'} {33, 'alex', 55, 'peiqi', 44} # 将f0里有的f1里不存在的取出 和 将f1里有的f0里不存在的取出,放在一个集合里;
4)以上几项还有个update功能,下面简介一下:
f0 = set(["seie",22,44,'alex','eric']) f1 = set(["seie",33,22,55,"eric","peiqi"]) f4 = f0.symmetric_difference(f1) f0.symmetric_difference_update(f1) print(f4) print(f0) 执行结果: {33, 'peiqi', 44, 55, 'alex'} {33, 55, 'alex', 'peiqi', 44} # 将执行结果赋值给f0,update更新了源值;
5) difference_update() 和 intersection_update() 同上,将比较集合获得的值,赋值给比较集合,被比较集合值不变;
set 就介绍到这里,想了解更多,看源码是最正确的选择。
在某些编程语言当中,函数声明和函数定义是区分开的(在这些编程语言当中函数声明和函数定义能够出如今不一样的文件中,好比C语言),可是在Python中,函数声明和函数定义是视为一体的。在Python中,函数定义的基本形式以下:
def function(params): block return expression/value
返回值不是必须的,若是没有return语句,则Python默认返回值None。建立函数时括号内的参数是形式参数,当调用时,使用的参数是实际参数。
1) 函数名必须如下划线或字母开头,能够包含任意字母、数字或下划线的组合。不能使用任何的标点符号;
2) 函数名是区分大小写的。
3) 函数名不能是保留字。
1)def 关键字,用来建立函数;
2)一个函数名function(): ,括号里能够放形式参数;
3)函数体(函数的内容),要记得给函数加注释,时间久了,可能会忘记函数是干什么的了;
4)返回值;
Python使用名称空间的概念存储对象,这个名称空间就是对象做用的区域, 不一样对象存在于不一样的做用域。下面是不一样对象的做用域规则:
1) 每一个模块都有自已的全局做用域。
2) 函数定义的对象属局部做用域,只在函数内有效,不会影响全局做用域中的对象。
3) 赋值对象属局部做用域,除非使用global关键字进行声明。
1) 大多数名字引用在三个做用域中查找:先局部(Local),次之全局(Global),再次以内置(Build-in)。
2) 如想在局部做用域中改变全局做用域的对象,必须使用global关键字。
3) 'global'声明把赋值的名字映射到一个包含它的模块的做用域中。
函数的参数是函数与外部沟通的桥梁,它可接收外部传递过来的值。
4) 在一个函数中对参数名赋值不影响调用者。
5) 在一个函数中改变一个可变的对象参数会影响调用者。
参数是对象指针,无需定义传递的对象类型。
默认参数给参数赋值:
def function(args=VALUE)
元组(Tuples)参数:
def function(*args)
字典(dictionary)参数:
def function(**kwargs)
默认值必须在非默认参数以后;
在单个函数定义中,只能使用一个tuple参数(*args)和一个字典参数(**kwargs)。
tuple参数必须在链接参数和默认参数以后。
字典参数必须在最后定义。
def login(username,password): ''' 用户登陆 :param username: 用户输入用户名 :param password: 用户输入密码 :return: ''' f = open('db',"r") for line in f: line_list = line.split("|") if line_list[0] == username and line_list[1] == password: return True return False def register(username,password): ''' 用户注册 :param username: 输入注册用户名 :param password: 输入注册密码 :return: None ''' f = open('db','a') temp = "\n" + username + "|" + password f.write(temp) f.close() def main(): t = input("Input 1.登陆,2.注册:") if t == '1': user = input("输入用户名:") pwd = input('输入密码:') r = login(user,pwd) if r: print('login OK') else: print("login faild") elif t == "2": user = input("输入用户名:") pwd = input('输入密码:') register(user,pwd)
这个简单的登陆、注册程序,由三个函数完成;
login()函数 : 1. 括号里的两个参数,是函数体里两个对应的两个参数,在括号里它是个(形式参数);就是说调用这个函数时,能够输入一个新的参数代替它们,这个新的参数,就是(实际参数);
2. 三引号内包含的就是注释信息,必定要写奥;
3. return,执行结果,要有一个返回值,让咱们知道,执行了什么或是执行结果是否成功;
register()函数:大概的意思和上面的差很少,只是没写返回值,不须要返回值的时候,就不用写了;
main()函数: 1. 它没有参数,可是它是一个主函数,经过执行main(),来调用上面两个函数;
2. login()函数里的(user,pwd) 就是实际参数,是真正的用户名和密码;register()使用 ,同login(),很少作解释;
备注: 刚刚这个小程序,是为了能更好的了解函数而写的简单例子,它更清楚的体现,函数的建立和使用过程,并非个标准的注册、登陆程序,真正的注册、登陆程序要复杂的多;
函数里尽可能不用print(),要使用return返回值;
咱们已经介绍过了,定义的函数参数是形式参数,只是一个引用。
函数参数的写法有多种,不一样写法,不一样调用,下面咱们详细说说函数参数的多种写法与调用;
def send(name,age): print(name,age) print("your name is:%s ,age is: %s" % (name,age)) return True # 调用send()参数 while True: name = input("input your name:") resolt = send(name,'19') if resolt == True: print("true") else: print("false")
# 利用返回值,作判断,执行结果是否成功;
默认参数: 程序里,send()函数调用时,从新传了两个实际参数,参数能够是变量,也能够是字符串、数字;这种按照顺序传参的方式,就是传入默认参数;
def send(name,age = 19):
print(name,age)
print("your name is:%s ,age is: %s" % (name,age))
return True
# 调用send()函数
while True:
name = input("input your name:")
resolt = send(name)
if resolt == True:
print("true")
else:
print("false")
# 执行结果:
input your name:long
long 19
your name is:long ,age is: 19
true
input your name:
# 建立函数时,参数age = 19 ,给age 赋了一个19的值,指定了参数的值,当调用的时候,只须要写入第一个参数就能够了;
默认参数之参数默认值: 在函数建立时,给某个参数赋了值(要注意一点,赋值的参数要放在最后,放在其它位置,调用函数后传参时会报错的),当调用时,能够不给赋值的参数传入新参数,若是传新参数,将覆盖原来的值;
说明:
元组类型参数(参数前加*)。一个函数里,只容许使用一个元组类型参数;形参带*是能够接收动态参数;
传入实际参数时,有两种方法:
1. 调用函数时,使用不加*的实际参数
说明:
1. 传入列表,把传入的列表做为此元组的一个元素传入,能够一次传入多个列表,每一个列表将是此元组的一个元素;
2. 传入元组,把传入的元组做为此元组的一个元素传入,能够一次传入多个元组,每一个元组将是此元组的一个元素;
3. 传入字符串或是数字,获得的结果是一个包含字符串或数字的元组;
4. 传入字典,把传入的字典做为此元组的一个元素传入,能够一次传入多个字典,每一个字典将是此元组的一个元素;
2. 调用函数时,使用加*的实际参数
说明:
1. 加*的实际参数,必须是可迭代类型如:列表、元组、字符串、字典等,数字不是可迭代的,不可使用;
2. 不加*执行结果:会把一整个列表、元组、字符串、字典做为一个元组元素使用;
3. 加*后执行结果:把列表、元组、字符串每个元素或字符,做为列表的元素,字典把每个key,做为元组元素使用;
4. 能够传入多个实际参数;
字典类型参数(参数前加**)。一个函数里,只容许使用一个字典类型参数,加*或**的都是可变长参数;
字典类型参数,两种传参方法:
1. 调用函数时,使用不加**的实际参数
说明:
1. (**kwargs)字典类型参数,不加**传入实际参数,必须是一个赋值形式的(像是一个变量)参数;
2. 能够传入多个参数,函数自动将传入的参数转成字典,每一个参数是字典里的一个元素;
2. 调用函数时,使用加**的实际参数
说明:
1. 加**传参,传入的参数必须是一个字典,执行的结果也是一个字典内容;
万能参数,实际是能够接收任何数值类型的传参,而后把字典类型的提取成字典参数,把元组类型的提出成元组参数;
函数的形参定义(*args,**kwargs):
说明:
def open(file, mode='r', buffering=None, encoding=None, errors=None, newline=None, closefd=True): # known special case of open """ Open file and return a stream. Raise IOError upon failure. file is either a text or byte string giving the name (and the path if the file isn't in the current working directory) of the file to be opened or an integer file descriptor of the file to be wrapped. (If a file descriptor is given, it is closed when the returned I/O object is closed, unless closefd is set to False.) mode is an optional string that specifies the mode in which the file is opened. It defaults to 'r' which means open for reading in text mode. Other common values are 'w' for writing (truncating the file if it already exists), 'x' for creating and writing to a new file, and 'a' for appending (which on some Unix systems, means that all writes append to the end of the file regardless of the current seek position). In text mode, if encoding is not specified the encoding used is platform dependent: locale.getpreferredencoding(False) is called to get the current locale encoding. (For reading and writing raw bytes use binary mode and leave encoding unspecified.) The available modes are: ========= =============================================================== Character Meaning --------- --------------------------------------------------------------- 'r' open for reading (default) 'w' open for writing, truncating the file first 'x' create a new file and open it for writing 'a' open for writing, appending to the end of the file if it exists 'b' binary mode 't' text mode (default) '+' open a disk file for updating (reading and writing) 'U' universal newline mode (deprecated) ========= =============================================================== The default mode is 'rt' (open for reading text). For binary random access, the mode 'w+b' opens and truncates the file to 0 bytes, while 'r+b' opens the file without truncation. The 'x' mode implies 'w' and raises an `FileExistsError` if the file already exists. Python distinguishes between files opened in binary and text modes, even when the underlying operating system doesn't. Files opened in binary mode (appending 'b' to the mode argument) return contents as bytes objects without any decoding. In text mode (the default, or when 't' is appended to the mode argument), the contents of the file are returned as strings, the bytes having been first decoded using a platform-dependent encoding or using the specified encoding if given. 'U' mode is deprecated and will raise an exception in future versions of Python. It has no effect in Python 3. Use newline to control universal newlines mode. buffering is an optional integer used to set the buffering policy. Pass 0 to switch buffering off (only allowed in binary mode), 1 to select line buffering (only usable in text mode), and an integer > 1 to indicate the size of a fixed-size chunk buffer. When no buffering argument is given, the default buffering policy works as follows: * Binary files are buffered in fixed-size chunks; the size of the buffer is chosen using a heuristic trying to determine the underlying device's "block size" and falling back on `io.DEFAULT_BUFFER_SIZE`. On many systems, the buffer will typically be 4096 or 8192 bytes long. * "Interactive" text files (files for which isatty() returns True) use line buffering. Other text files use the policy described above for binary files. encoding is the name of the encoding used to decode or encode the file. This should only be used in text mode. The default encoding is platform dependent, but any encoding supported by Python can be passed. See the codecs module for the list of supported encodings. errors is an optional string that specifies how encoding errors are to be handled---this argument should not be used in binary mode. Pass 'strict' to raise a ValueError exception if there is an encoding error (the default of None has the same effect), or pass 'ignore' to ignore errors. (Note that ignoring encoding errors can lead to data loss.) See the documentation for codecs.register or run 'help(codecs.Codec)' for a list of the permitted encoding error strings. newline controls how universal newlines works (it only applies to text mode). 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 closefd is False, the underlying file descriptor will be kept open when the file is closed. This does not work when a file name is given and must be True in that case. A custom opener can be used by passing a callable as *opener*. The underlying file descriptor for the file object is then obtained by calling *opener* with (*file*, *flags*). *opener* must return an open file descriptor (passing os.open as *opener* results in functionality similar to passing None). open() returns a file object whose type depends on the mode, and through which the standard file operations such as reading and writing are performed. When open() is used to open a file in a text mode ('w', 'r', 'wt', 'rt', etc.), it returns a TextIOWrapper. When used to open a file in a binary mode, the returned class varies: in read binary mode, it returns a BufferedReader; in write binary and append binary modes, it returns a BufferedWriter, and in read/write mode, it returns a BufferedRandom. It is also possible to use a string or bytearray as a file for both reading and writing. For strings StringIO can be used like a file opened in a text mode, and for bytes a BytesIO can be used like a file opened in a binary mode. """ pass
操做文件时,通常须要经历以下步骤:
文件句柄 = open('文件路径', '模式')
注:python中打开文件有两种方式,即:open(...) 和 file(...) ,本质上前者在内部会调用后者来进行文件操做,推荐使用 open。Python3,没有file() ;
打开文件时,须要指定文件路径和以何等方式打开文件,打开后,便可获取该文件句柄,往后经过此文件句柄对该文件操做。
打开文件的模式有:
"+" 表示能够同时读写某个文件
"U"表示在读取时,能够将 \r \n \r\n自动转换成 \n (与 r 或 r+ 模式同使用)
"b"表示处理二进制文件(如:FTP发送上传ISO镜像文件,linux可忽略,windows处理二进制文件时需标注)
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 0 (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. """
f = open("file",'r+',encoding="utf-8")
# 若是打开方式无b,默认read()读取所有,按照字符读取,有b,按照字节读取,括号里有数值,从数值位置读;
f.read(1)
# tell 当前指针所在的位置(字节)
print (tell())
# seek调整当前指针的位置(字节);
f.seek(tell())
# 当前指针位置向后覆盖写入
f.write("hello,world !")
# 关闭文件;
f.close()
为了不打开文件后忘记关闭,能够经过管理上下文,即:
with open('log','r') as f: ...
如此方式,当with代码块执行完毕时,内部会自动关闭并释放文件资源。
在Python 2.7 后,with又支持同时对多个文件的上下文进行管理,即:
with open('log1') as obj1, open('log2') as obj2: pass
实例,再也不须要关闭文件:
with open('db1', 'r', encoding="utf-8") as f1, open("db2", 'w',encoding="utf-8") as f2: for line in f1: new_str = line.replace("alex", 'st') f2.write(new_str)
内置函数,详细信息,请点击连接:https://docs.python.org/2/library/functions.html
abs()
取绝对值 ,如 abs(-12) 结果:12
all(iterable) 若是iterable全部的元素返回True,或是iterable是空(空列表也是空,可是结尾加了分割符,变成元素就不同了),返回True;
若是iterable的全部元素不为0、''、()、{}、[]、None、False或者iterable为空,all(iterable)返回True,不然返回False;参数iterable:可迭代对象;
如: 返回值是False的: all([None,12,])、all([0,12,])、all([12,''])等
返回值是True的: all([])、all(())、等
实例:
>>> all(([],{})) False >>> all(([],)) False
>>> all([])
True >>> all(([])) # 这块我不是很明白,不纠结了,知道是这样的,不要犯错误就好了;我认为这是个bug; True
>>>all(([[]])) #
False
>>> all(('ak'))
True
注意: 空元组、空列表返回值为True,可是 空元组、空列表做为元素时返回False,这里要特别注意,可是要加,号;
any(iterable) 返回False: if any element of the iterable is true. If the iterable is empty.
若是iterable的任何元素不为0、''、False,all(iterable)返回True。若是iterable为空,返回False; 参数iterable:可迭代对象;
如: 返回值是False的:any(['',None,0,[],()])
返回值是True的:any(("",None,"Eric",12))
实例:
>>> any(([],12)) True >>> any(([],)) False >>> any(([])) False
bytes([source[, encoding[, errors]]]) 二进制数据由bytes类型表示。
Return a new “bytes” object, which is an immutable sequence of integers in the range 0 <= x < 256. bytes is an immutable version of bytearray.
1) Python 3会假定咱们的源码 — 即.py文件 — 使用的是UTF-8编码方式。Python 2里,.py文件默认的编码方式为ASCII。可使用# -*- coding: windows-1252 -*-方式
来改变文件的编码。若是py文件中包含中文的字符串,则须要制定为# -*- coding: gbk -*-,貌似默认的utf8不够哦。
2) python3中默认的str为unicode的,可使用str.encode来转为bytes类型。
3) python3的print函数只支持unicode的str,貌似没有对bytes的解码功能,因此对对不能解码的bytes不能正确输出。
4) str和bytes不能链接和比较。
5) codecs仍然能够用来str和bytes间的转化。
6) 定义非ascii码的bytes时,必须使用如 bytes('中国','gbk') 来转码。
>>> bytes(12) b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' >>> bytes('as','utf-8') b'as' >>> bytes('as','gbk') b'as'