Python学习之旅 —— 基础篇(三)set集合、自定义函数、文件操作

本篇要点:
数据类型:set集合
自定义函数
文件操作
三元运算(三目运算)和lambda表达式
 
一、set集合
     python中数据类型的一种,是无序并且不重复的数据集合。set源码:
class set(object):
    """
     创建set集合
    set() -> new empty set object
     把可迭代的数据类型转换成元组
    set(iterable) -> new set object
    
    Build an unordered collection of unique elements.
    """
>>> s1 = {11, 22, 33}
>>> print(s1,type(s1))
{33, 11, 22} <class 'set'>
 
>>> l1 = [2, 3, 4,]
>>> s1 = set(l1)
>>> print(l1,type(l1))
[2, 3, 4] <class 'list'>
>>> print(s1,type(s1))
{2, 3, 4} <class 'set'>
View Code
    # 向集合中增加元素,如果存在,不做任何操作。
    def add(self, *args, **kwargs): # real signature unknown
        """
        Add an element to a set.
        
        This has no effect if the element is already present.
        """
        pass
>>> s1 = {11, 22, 33}
>>> s1.add(44)
>>> print(s1)
{33, 11, 44, 22}
View Code
# 清空集合中所有的元素
    def clear(self, *args, **kwargs): # real signature unknown
        """ Remove all elements from this set. """
        pass
>>> s1 = {11, 22, 33}
>>> print(s1)
{33, 11, 22}
>>> s1.clear()
>>> print(s1)
set()
View Code
# 浅复制一个集合 只拷贝第一层
    def copy(self, *args, **kwargs): # real signature unknown
        """ Return a shallow copy of a set. """
        pass
 
    # s1.difference(s2) 找到在s1中有,s2中没有的元素,并保存到一个新的集合
    def difference(self, *args, **kwargs): # real signature unknown
        """
        Return the difference of two or more sets as a new set.
        
        (i.e. all elements that are in this set but not the others.)
        """
        pass
>>> s1 = {11,22,33,}
>>> s2 = {22,33,44,}
>>> s3 = s1.difference(s2)
>>> print("%s \n%s \n%s" % (s1,s2,s3))
{33, 11, 22} 
{33, 44, 22}
{11}
View Code
# s1.difference(s2) 找到在s1中有,s2中没有的元素,把结果更新到s1中
    def difference_update(self, *args, **kwargs): # real signature unknown
        """ Remove all elements of another set from this set. """
        pass
>>> s1 = {11,22,33,}
>>> s2 = {22,33,44,}
>>> s1.difference_update(s2)
>>> print("%s \n%s" % (s1,s2))
{11}
{33, 44, 22}
View Code 
# s1.intersection(s2) 找到即在集合s1中,又在集合s2中的元素,并把结果保存到一个新的集合里。
    def intersection(self, *args, **kwargs): # real signature unknown
        """
        Return the intersection of two sets as a new set.
        
        (i.e. all elements that are in both sets.)
        """
        pass
>>> s1 = {11,22,33,}
>>> s2 = {22,33,44,}
>>> s3 = s1.intersection(s2)
>>> print("%s \n%s \n%s" % (s1,s2,s3))
{33, 11, 22} 
{33, 44, 22}
{33, 22}
View Code
# s1.intersection(s2) 找到即在集合s1中,又在集合s2中的元素,并把结果更新到s1中
    def intersection_update(self, *args, **kwargs): # real signature unknown
        """ Update a set with the intersection of itself and another. """
        pass
>>> s1 = {11,22,33,}
>>> s2 = {22,33,44,}
>>> s1.intersection_update(s2)
>>> print("%s \n%s" % (s1,s2))
{33, 22}
{33, 44, 22}
View Code 

  # 判断两个集合是否有交接,没有交集时返回True,有交集时返回False

    def isdisjoint(self, *args, **kwargs): # real signature unknown
        """ Return True if two sets have a null intersection. """
        pass
>>> s1 = {11,22,33,}
>>> s2 = {22,33,44,}
>>> s3 = {1,2,3,}
>>> s1.isdisjoint(s2)
False
>>> s1.isdisjoint(s3)
True
View Code

 # s1.issubset(s2) 判断s1是不是s2的子集

    def issubset(self, *args, **kwargs): # real signature unknown
        """ Report whether another set contains this set. """
        pass
>>> s1 = {11,22,}
>>> s2 = {11,22,33,44,}
>>> s3 = {22,33,}
>>> s1.issubset(s2)
True
>>> s1.issubset(s3)
False
View Code
# s1.issuperset(s2) 判断s1是不是s2的父集
    def issuperset(self, *args, **kwargs): # real signature unknown
        """ Report whether this set contains another set. """
        pass
>>> s1 = {11,22,33,44,55}
>>> s1 = {11,22,33,44,55,}
>>> s2 = {22,33,55,}
>>> s3 = {44,33,66,}
>>> s1.issuperset(s2)
True
>>> s1.issuperset(s3)
False
View Code

# 任意删除并返回一个元素
    def pop(self, *args, **kwargs): # real signature unknown
        """
        Remove and return an arbitrary set element.
        Raises KeyError if the set is empty.
        """
        pass
>>> s1 = {11,22,33,44,55,}
>>> s1.pop()
33
View Code
    # 删除指定的一个元素,这个元素必须在集合中,否则报错。区别于discard()
    def remove(self, *args, **kwargs): # real signature unknown
        """
        Remove an element from a set; it must be a member.
        
        If the element is not a member, raise a KeyError.
        """
        pass
>>> s1 = {11,22,33,}
>>> s1.remove(11)
>>> print(s1)
{33, 22}
>>> s1.remove(44)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 44
View Code
    # 删除指定的一个元素,如果元素不存在不报错。可以起到判断元素是否在集合中时,代码不报错的作用。
    def discard(self, *args, **kwargs): # real signature unknown
        """
        Remove an element from a set if it is a member.
        
        If the element is not a member, do nothing.
        """
        pass
>>> s1 = {11,22,33,}
>>> s1.discard(11)
>>> print(s1)
{33, 22}
>>> s1.discard(44)   # 44 不在s1中,操作时不报错
>>> print(s1)
{33, 22}
View Code
# 相当于取两个集合的并集,再把他俩的交集删掉。返回这个新集合。
    def symmetric_difference(self, *args, **kwargs): # real signature unknown
        """
        Return the symmetric difference of two sets as a new set.
        
        (i.e. all elements that are in exactly one of the sets.)
        """
        pass
>>> s1 = {11,22,33,44,}
>>> s2 = {22,44,55,66}
>>> s3 = s1.symmetric_difference(s2)
>>> print("%s \n%s \n%s" % (s1,s2,s3))
{33, 11, 44, 22} 
{66, 44, 22, 55} 
{33, 66, 11, 55}
View Code
    # s1.symmetric_difference_update(s2) 相当于取s1,s2两个集合的并集,再把他俩的交集删掉。结果赋值给s1
    def symmetric_difference_update(self, *args, **kwargs): # real signature unknown
        """ Update a set with the symmetric difference of itself and another. """
        pass
>>> s1 = {11,22,33,44,}
>>> s2 = {22,44,55,66}
>>> s1.symmetric_difference_update(s2)
>>> print("%s \n%s" % (s1,s2))
{33, 66, 11, 55} 
{66, 44, 22, 55}
View Code
    # 取两个集合的并集,结果返回到一个新集合中。
    def union(self, *args, **kwargs): # real signature unknown
        """
        Return the union of sets as a new set.
        
        (i.e. all elements that are in either set.)
        """
        pass
>>> s1 = {11,22,33,44,}
>>> s2 = {22,44,55,66}
>>> s3 = s1.union(s2)
>>> print("%s \n%s \n%s" % (s1,s2,s3))
{33, 11, 44, 22} 
{66, 44, 22, 55}
{33, 66, 11, 44, 22, 55}
View Code
# s1.update(s2) 去两个集合的并集,将结果赋值给s1
    def update(self, *args, **kwargs): # real signature unknown
        """ Update a set with the union of itself and others. """
        pass
>>> s1 = {11,22,33,44,}
>>> s2 = {22,44,55,66}
>>> s1.update(s2)
>>> print("%s \n%s" % (s1,s2))
{33, 66, 11, 44, 22, 55}
{66, 44, 22, 55}
View Code

 

二、自定义函数

为什么要创建函数?
提升代码的复用性和可读性
# 使用函数前,是面向过程变成,更具逻辑从上到下一行一行执行。
while True:
    if cpu利用率 > 90%:
        #发送邮件提醒
        连接邮箱服务器
        发送邮件
        关闭连接
  
    if 硬盘使用空间 > 90%:
        #发送邮件提醒
        连接邮箱服务器
        发送邮件
        关闭连接
  
    if 内存占用 > 80%:
        #发送邮件提醒
        连接邮箱服务器
        发送邮件
        关闭连接
sendmail函数(使用参数前)
# 使用函数后,就变成函数式,面向对象编程
def 发送邮件(内容)
    #发送邮件提醒
    连接邮箱服务器
    发送邮件
    关闭连接
  
while True:
  
    if cpu利用率 > 90%:
        发送邮件('CPU报警')
  
    if 硬盘使用空间 > 90%:
        发送邮件('硬盘报警')
  
    if 内存占用 > 80%:
        发送邮件('内存报警')
 
sendmail函数(使用参数后)
函数式:将某功能代码封装到函数中,日后便无需重复编写,仅调用函数即可
面向对象:对函数进行分类和封装
 
1、函数的定义
def 函数名(参数):
    函数体
    return
a、def——python中表示函数的关键字
b、函数名——定义函数名称,以后根据函数名称来调用函数
c、(参数)——为函数提供数据
d、函数体——定义在函数中的一系列逻辑计算,函数具体功能的代码实现,写在这个里面
e、返回值(return)——当函数执行完毕后,给调用者返回数据
 
示例1:邮件发送函数
def sendmail():
    import smtplib
    from email.mime.text import MIMEText
    from email.utils import formataddr

    msg = MIMEText('邮件内容', 'plain', 'utf-8')
    msg['From'] = formataddr(["武沛齐", 'wptawy@126.com'])
    msg['To'] = formataddr(["走人", '424662508@qq.com'])
    msg['Subject'] = "主题"

    server = smtplib.SMTP("smtp.126.com", 25)
    server.login("wptawy@126.com", "WW.3945.5")
    server.sendmail('wptawy@126.com', ['1042665@qq.com', ], msg.as_string())
    server.quit()
sendmail()
sendmail()——无参数
 
2、参数的使用
示例1中,实现了给1042665@qq.com发用邮件的功能。但是如果我想要给不同的收件人发邮件,就要写好多个函数,起不到复用代码的效果。因此加上参数。
def sendmail(user_email):  # user_email 叫做函数sendmail的形式参数,简称形参
    import smtplib
    from email.mime.text import MIMEText
    from email.utils import formataddr

    msg = MIMEText('邮件内容', 'plain', 'utf-8')
    msg['From'] = formataddr(["武沛齐", 'wptawy@126.com'])
    msg['To'] = formataddr(["走人", '424662508@qq.com'])
    msg['Subject'] = "主题"

    server = smtplib.SMTP("smtp.126.com", 25)
    server.login("wptawy@126.com", "WW.3945.5")
    server.sendmail('wptawy@126.com', [user_email, ], msg.as_string())
    server.quit()
sendmail("1042665@qq.com”)  # 1042665@qq.com叫做sendmail的实际参数,调用sendmail函数时把这个参数传递给函数来执行。叫做实际参数,简称实参
sendmail(“test1@test.com")
sendmail(“test2@test.com")
sendmail(user_email)——有参数
引入参数后,就可以给上面三个邮箱发送邮件,而不用定义多个函数。
 
3、多个参数的使用和返回值
示例2:登陆、注册函数
def login(username, password):
    """
    用于用户登陆
    :param username: 用户输入的用户名
    :param password: 用户输入的密码
    :return: True,登陆成功;False,登录失败
    """
    with open("db", "r") as f:
        for i in f:
            user_pwd_list = i.strip().split(",")
            if username == user_pwd_list[0] and password == user_pwd_list[1]:
                return True
    return False


def register(username, password):
    """
     用于用户注册
    :param username: 用户输入的用户名
    :param password:  用户输入的密码
    :return: None
    """
    item = "\n{username},{password}".format(username=username, password=password)
    with open("db", "a") as f:
        f.write(item)
    print("注册成功")


def main():
    """
    用于程序执行的入口
    :return:  默认返回None
    """
    choice = input("[1:登陆],[2:注册],请输入数字编号:")
    user = input("请输入用户名:")
    pwd = input("请输入密码:")
    if choice == "1":
        t = login(user, pwd)  # 函数的return返回值赋值给t
        if t is True:
            print("登陆成功")
        else:
            print("登陆失败")

    elif choice == "2":
        register(user, pwd)

main()
登陆注册
示例中定义了三个函数,login、register、main。前两个函数需要传递用户名和密码两个参数才能正常完成用户的登陆和验证。因此设定两个形参,让调用者传递两个实参来实现功能。而main函数中,函数的返回值赋值给了t,通过对t的值进行判断,实现了打印不同内容的功能。
 
4、函数参数的更多类型
上面两个示例都是对普通参数的使用,参数还有更多类型,下面一一说明。
# 普通参数
def send(email, user, msg):
    print('发送成功', email, user, msg)
    return True

res = send("1042665@qq.com", "Pesen", "发送成功”)  # 传递实参时,要按照形参指定的顺序来填写,否则使用了错误的参数,程序很有可能会出现错误。
if res is True:
    print("发送成功")
else:
    print("发送失败")
View Code
# 默认参数(默认参数必须放到最后定义,否则会报错)
def send(email, user=“Pesen", msg="发送成功”):  # 给user、msg两个形参指定默认值
    print('发送成功', email, user, msg)
    return True

res = send("1042665@qq.com”)  # 不给send函数传递user,msg的实参,会使用默认值
if res is True:
    print("发送成功")
else:
    print("发送失败")
View Code
# 指定参数:可以打破实参传递的顺序
def send2(email, user, msg):
    print("邮件信息:", email, user, msg)
send2(user="Pesen", msg="OK", email="104266@qq.com")
View Code
# 动态参数
*args 传入的参数保存到元组中
>>> def f1(*args):
...   print(args)
...
>>> li = [11,22,33,44,]
>>> f1(li)  # 把li作为普通参数传递给函数时,列表li作为一个元组中的一个元素
([11, 22, 33, 44],)
>>> f1(*li)  # 加上*,使用动态参数时,把列表中每一个元素作为元组的每一个元素
(11, 22, 33, 44)
**kwargs 传入的实参保存到字典中,要遵循key:value的格式
>>> def f1(**kwargs):
...   print(kwargs)
...
>>> f1(k1="v1", k2="v2")
{'k2': 'v2', 'k1': 'v1'}
>>> dic = {"k3": "v3", "k4": "v4",}
>>> f1(**dic)
{'k4': 'v4', 'k3': 'v3'}
View Code
# 万能参数  传入的参数按照特点自动判断使用哪种方式处理
>>> def f1(*args, **kwargs):
...     print(args)
...     print(kwargs)
...
>>> f1(11, 22, 33, "ww", k1="v1", k2="v2")
(11, 22, 33, 'ww')
{'k2': 'v2', 'k1': 'v1'}
View Code

示例:str的format(*args, **kwargs)函数
>>> s1 = "My name is {0}, {1} years old.".format("Pesen", 18)
>>> print(s1)
My name is Pesen, 18 years old.
>>>
>>> s2 = "My name is {0}, {1} years old.".format(*["Pesen", 18])
>>> print(s2)
My name is Pesen, 18 years old.
>>>
>>> s3 = "My name is {name}, {age} years old.".format(name="Pesen", age=20)
>>> print(s3)
My name is Pesen, 20 years old.
>>>
>>> s4 = "My name is {name}, {age} years old.".format(**{"name": "Pesen", "age": 20})
>>> print(s4)
My name is Pesen, 20 years old.
View Code
5、函数使用的一些补充
‘''
函数定义
python是自上到下来执行代码,f1函数第一次定义时,把函数体、参数等等信息存放到内存块A中,函数名f1指向内存块A;
下面又对f1进行了定义,这次定义的内容存放到内存块B中,然后修改了f1的指向,指向了内存块B。
‘''
def f1(a1, b1):
    print(a1 + b1)

def f1(a1, b1):
    print(a1 * b1)
f1(4, 5)  # 结果是20,执行的是后面定义的函数f1
‘''
参数传递
传递的是引用,而不是再复制一份
‘''
def f1(a1):
    a1.append(999)
 
li = [1,2,3,4,]  # li是全局变量,从这个例子中可以看出,函数的局部作用域可以对全局变量的进行修改。
f1(li) 
print(li) # 最终li中增加了999这个元素
 
全局变量
# 全局变量在所有作用域中都可读
# 优先使用自己定义的局部变量,找不到去找全局变量。
# 重新赋值全局变量:局部作用域中加上 global 变量
# 局部作用域中,如果全局变量是一个字典、list,可以 通过对字典和list的操作去修改,但是不能重新赋值(不用加global)
# 定义全局变量,要全部用大写: NAME = 'Pesen'
 
# 定义全局变量,潜规则:所有字母都大写
NAME = 'Pesen'
 
# 全局变量可以直接被所有作用于调用
>>> def f1():
...     print(NAME)
...
>>> f1()
pesen
 
# 如果函数中定义了局部变量NAME,优先使用局部变量,全局变量不会被修改。
>>> NAME = "pesen"
>>> def f1():
...   NAME = "xie"
...   print(NAME)
...
>>> f1()
tie  # 优先使用局部变量
>>> print(NAME)
pesen # 全局变量不会被修改
 
# 如果要给全局变量重新赋值,可以通过global实现
>>> NAME = "pesen"
>>> def f1():
...   global NAME
...   NAME = "xie"
...   print(NAME)
...
>>> f1()
xie
>>> print(NAME)
xie # 全局变量被重新复制为"xie" 
 
三、三元运算(三目运算)和lambda表达式
1、三元运算
# 传统模式
a = input("请输入1")
if a == "1":
    name = "Pesen"
else:
   name = "Xie"
print(name)

# 三元运算 对if else 的简写
a = input("请输入1")
name = "Pesen" if a == "1" else "Xie"
print(name)
 
2、lambda表达式
# 传统方式
def f1(a1,a2=10):
    return a1 + a2 + 100
res = f1(20)
print(res)

# lambda 表达式 函数的简单表达
f1 = lambda a1, a2=10: a1 + a2 + 100
res = f1(20)
print(res)
 
四、文件操作
python通过open()函数来打开文件
两种使用方式:
# 打开文件,操作文件,关闭文件
f = open('/root/file.txt', 'r')
f.read()
f.close()
 
# with方式可以在结束后自动关闭文件
with open('/root/file.txt', 'r') as f:
    f.read()
 
1、open()函数源码
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 # 二进制方式打开,可以rb/wb/xb/ab方式使用
    't'       text mode (default) # 默认的文字模式
    '+'       open a disk file for updating (reading and writing) # 最常用的是r+,读写,其他不常用。
    'U'       universal newline mode (deprecated) # python3中已经弃用
    ========= ===============================================================
   
    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
 
View Code

 

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 detach(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
        pass
    # 读整个文件内容,返回一个大string
    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
View Code
 
文件读写小练习:
with open("db", "r+") as file1:
    data = file1.read(2) # 字符
    file1.tell()  # 获取当前指针位置(字节)
    file1.seek(file1.tell())  # 修改指针位置(字节)
    file1.write("1044")
print(data)
 
3、同时打开多个文件
python2.7之后支持同时打开多个文件
示例:备份文件
with open("db", "r") as file01, open("db.bak", "x") as file02:
    for i in file01: # 读取db文件的每一行,写入到db.bak文件,如果db.bak文件存在,报错,不做操作
        file02.write(i)
       
with open("db.bak", "r") as f:
    res = f.read()

print(res)
 
 
 

 

posted on 2016-05-23 22:30  Pesen  阅读(933)  评论(0编辑  收藏  举报

导航