Day03基础(三)

Python 基础(三)

简介:

  本章,我们详细了解下,set集合使用、Python的函数相关功能及使用、open函数功能使用及其他(with,内置函数)功能使用;

一. Python的set 集合

1. 首先创建一个集合,然后再说说集合的特性,最后做个小结

创建集合有两种方式:

1) 直接创建

se = {"jihe",22,"long",18} 或是 se = {"jihe",22,"long",18,18,22}  # print(se) 执行结果: {18, 'jihe', 'long', 22}

2)使用set创建

li = ["jihe",22,"long",18,22,"jihe"]    

li = set(li)   或是  li = set(["jihe",22,"long",18,22,"jihe"])              # print(li) 执行结果:{18, 'long', 'jihe', 22} 

惊奇的发现,结果竟然相同(虽然位置不同),这是为什么呢?

接下来,聊聊集合的特性,一切将迎刃而解。

通过执行结果,我们可以看到两种现象:

          1) 执行的结果是无序的,不是按照我们赋值的顺序排列的;

          2) 是不重复的序列, 重复的值,只记录一次;

小结:

  1. 集合是{}中包含(不可变类型元素)字符串或数字类型的一个序列;  如果{}有列表、字典,就会报错;元组不会报错,因为它是不可变类型;

  2. 集合可以用set()创建,内容包含可迭代的对象;如列表、字符串、元组等,如果是字典,只使用Keys; 数字不可以,因为数字是不可迭代的;

  3. 集合是无序的(这点和字典一样),元素不重复,每一个元素都是唯一的;

2. 集合的主要功能使用

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 就介绍到这里,想了解更多,看源码是最正确的选择。

二. python 函数

 一. 函数的定义

1. 函数定义的基本形式   

  在某些编程语言当中,函数声明和函数定义是区分开的(在这些编程语言当中函数声明和函数定义可以出现在不同的文件中,比如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关键字进行声明。

  • LGB(名称查找规则)规则是Python查找名字的规则,下面是LGB规则:

  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参数必须在连接参数和默认参数之后。

  字典参数必须在最后定义。

3. 借用登录、注册小程序,详细讲解下函数:

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 = "
" + 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返回值;

4. 函数参数

我们已经介绍过了,定义的函数参数是形式参数,只是一个引用。

函数参数的写法有多种,不同写法,不同调用,下面我们详细说说函数参数的多种写法与调用;

1)默认参数
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的值,指定了参数的值,当调用的时候,只需要写入第一个参数就可以了;

默认参数之参数默认值: 在函数创建时,给某个参数赋了值(要注意一点,赋值的参数要放在最后,放在其它位置,调用函数后传参时会报错的),当调用时,可以不给赋值的参数传入新参数,如果传新参数,将覆盖原来的值;

2) 指定参数

 

说明:

  1. 执行了两个send()函数,执行结果是一样的,第一个是,使用默认参数,第二个使用指定参数;
  2. send函数有两个参数,当调用send()函数时,使用关键字参数,指定了参数内容,这种指定参数的传参方法,调用函数时参数位置不受限制;
3)元组类型参数

元组类型参数(参数前加*)。一个函数里,只允许使用一个元组类型参数;形参带*是可以接收动态参数;

传入实际参数时,有两种方法:

1. 调用函数时,使用不加*的实际参数

说明:

  1. 传入列表,把传入的列表作为此元组的一个元素传入,可以一次传入多个列表,每个列表将是此元组的一个元素;

  2. 传入元组,把传入的元组作为此元组的一个元素传入,可以一次传入多个元组,每个元组将是此元组的一个元素;

  3. 传入字符串或是数字,得到的结果是一个包含字符串或数字的元组;

  4. 传入字典,把传入的字典作为此元组的一个元素传入,可以一次传入多个字典,每个字典将是此元组的一个元素;

2. 调用函数时,使用加*的实际参数

说明: 

  1. 加*的实际参数,必须是可迭代类型如:列表、元组、字符串、字典等,数字不是可迭代的,不可以使用

  2. 不加*执行结果:会把一整个列表、元组、字符串、字典作为一个元组元素使用;

  3. 加*后执行结果:把列表、元组、字符串每一个元素或字符,作为列表的元素,字典把每一个key,作为元组元素使用;

  4. 可以传入多个实际参数;

4)字典类型参数

字典类型参数(参数前加**)。一个函数里,只允许使用一个字典类型参数,加*或**的都是可变长参数;

字典类型参数,两种传参方法:

1. 调用函数时,使用不加**的实际参数

 说明:

  1. (**kwargs)字典类型参数,不加**传入实际参数,必须是一个赋值形式的(像是一个变量)参数;

  2.  可以传入多个参数,函数自动将传入的参数转成字典,每个参数是字典里的一个元素;

2. 调用函数时,使用加**的实际参数

说明:

  1. 加**传参,传入的参数必须是一个字典,执行的结果也是一个字典内容;

 5)万能参数(*args,**kwargs)

万能参数,实际是可以接收任何数值类型的传参,然后把字典类型的提取成字典参数,把元组类型的提出成元组参数;

函数的形参定义(*args,**kwargs):

说明:

  1.  万能参数,不是官方说的。 函数接收参数的形式是万能的,给了这个定义;
  2.  传入的实际参数,可以是任何数值类型,函数会将得到的参数自行分为两类;
  3.  分为:元组类型的参数,字典类型的参数; 

三. open 函数功能

1.  open()函数功能源码注释 py3:

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, '', '
', '
', and '
'.  It works as
    follows:
    
    * On input, if newline is None, universal newlines mode is
      enabled. Lines in the input can end in '
', '
', or '
', and
      these are translated into '
' 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 '
' characters written are
      translated to the system default line separator, os.linesep. If
      newline is '' or '
', no translation takes place. If newline is any
      of the other legal values, any '
' 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

2. open()函数,操作文件使用,同(file)

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

  • 打开文件
  • 操作文件

2.1  打开文件

文件句柄 = open('文件路径', '模式'

注:python中打开文件有两种方式,即:open(...) 和  file(...) ,本质上前者在内部会调用后者来进行文件操作,推荐使用 open。Python3,没有file() ;

打开文件时,需要指定文件路径和以何等方式打开文件,打开后,即可获取该文件句柄,日后通过此文件句柄对该文件操作。

打开文件的模式有:

  • r,只读模式(默认)。
  • w,创建新文件,(如果文件存在,清空内容)只写模式。【不可读;不存在则创建;存在则删除内容;】
  • a,追加模式。【可读;   不存在则创建;存在则只追加内容;】

"+" 表示可以同时读写某个文件

  • r+,可读写文件。【可读;可写;可追加】
  • w+,创建新文件,(如果文件存在,清空内容)读写模式。
  • a+,同a

"U"表示在读取时,可以将 自动转换成 (与 r 或 r+ 模式同使用)

  • rU
  • r+U

"b"表示处理二进制文件(如:FTP发送上传ISO镜像文件,linux可忽略,windows处理二进制文件时需标注)

  • rb
  • wb
  • ab

2.2 操作功能

    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.
        """

2.3 open操作文件 之 实例:

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 功能使用

为了避免打开文件后忘记关闭,可以通过管理上下文,即:

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 < 256bytes 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'x00x00x00x00x00x00x00x00x00x00x00x00'
>>> bytes('as','utf-8')
b'as'
>>> bytes('as','gbk')
b'as'

  

  

原文地址:https://www.cnblogs.com/liuhailong-py-way/p/5519616.html