您的位置:新葡亰496net > 奥门新萄京娱乐场 > 新葡亰496net:python之文件操作,文件操作以及序

新葡亰496net:python之文件操作,文件操作以及序

发布时间:2019-06-16 03:47编辑:奥门新萄京娱乐场浏览(154)

    管理器连串分为:硬件,操作系统,应用程序

    一. 文书操作基本流程

    Computer种类分为:计算机硬件,操作系统,应用程序三局地。

    咱俩用python或其余语言编写的应用程序若想要把数据恒久保存下去,必供给保存于硬盘中,那就涉嫌到应用程序要操作硬件,举世闻明,应用程序是无能为力直接操作硬件的,那就用到了操作系统。操作系统把纷纷的硬件操作封装成轻巧的接口给用户/应用程序使用,其汉语件正是操作系统提供给应用程序来操作硬盘虚拟概念,用户或应用程序通过操作文件,能够将和谐的数额永远保存下来。

    有了文本的概念,大家无需再去思量操作硬盘的细节,只供给关切操作文件的流程:

    #1. 打开文件,得到文件句柄并赋值给一个变量
    f=open('a.txt','r',encoding='utf-8') #默认打开模式就为r
    
    #2. 通过句柄对文件进行操作
    data=f.read()
    
    #3. 关闭文件
    f.close()
    

    一,文件操作基本流程。

    微型Computer类别分为:Computer硬件,操作系统,应用程序三片段。

    大家用python或别的语言编写的应用程序若想要把多少永世保存下去,须要求封存于硬盘中,那就事关到应用程序要操作硬件,赫赫有名,应用程序是心有余而力不足直接操作硬件的,那就用到了操作系统。操作系统把纷纭的硬件操作封装成简单的接口给用户/应用程序使用,其粤语件就是操作系统提须要应用程序来操作硬盘虚拟概念,用户或应用程序通过操作文件,能够将团结的数量长久保存下来。

    有了文本的概念,大家不供给再去思念操作硬盘的细节,只须求关切操作文件的流程:

    #1. 打开文件,得到文件句柄并赋值给一个变量
    f=open('a.txt','r',encoding='utf-8') #默认打开模式就为r
    
    #2. 通过句柄对文件进行操作
    data=f.read()
    
    #3. 关闭文件
    f.close()
    

     

    再次来到目录页

    1. 文件a.txt内容:每一行内容分别为商品名字,价钱,个数。

    apple 10 3
    tesla 100000 1
    mac 3000 2
    lenovo 30000 3
    chicken 10 3
    透过代码,将其创设成这种数据类型:
    [{'name':'apple','price':10,'amount':3},
    {'name':'tesla','price':1000000,'amount':1}......] 并盘算出总价钱。

    答:

    li = []
    with open('a.txt', encoding='utf-8', mode='r') as f1:
        for i in f1:
            l2 = i.strip().split()
            dic = {'name':l2[0], 'price':l2[1], 'amount':l2[2]}
            li.append(dic)
    print(li)
    sum = 0
    for j in li:
        sum = sum   int(j['price']) * int(j['amount'])
    print(sum)
    
    优化扩展代码如下:
    name_list = ['name', 'price', 'amount']
    li = []
    with open('a.txt', encoding='utf-8', mode='r') as f1:
        for i in f1:
            l2 = i.strip().split()
            # dic = {}
            # for j in range(len(l2)):
            #     dic[name_list[j]] = l2[j]
            dic = dict(zip(name_list, l2)) # 前面三句可以优化成这一句,易读性也更强
            li.append(dic)
    print(li)
    sum = 0
    for k in li:
        sum = sum   int(k['price']) * int(k['amount'])
    print(sum)
    

    2,有如下文件:

    -------
    alex是老男孩python发起人,创建人。
    alex其实是人妖。
    谁说alex是sb?
    你们真逗,alex再牛逼,也掩饰不住资深屌丝的气质。
    ----------
    

    将文件中持有的alex都替换到大写的SB。

    import os
    with open('alex.txt', encoding='utf-8', mode='r') as f1,
        open('SB.txt', encoding='utf-8', mode='w') as f2:
        for i in f1:
            print(i)
            new_i = i.replace('alex', 'SB')
            f2.write(new_i)
    os.remove('alex.txt')
    os.rename('SB.txt', 'alex.txt')
    

    硬件:目的在于运营软件发生的授命。硬件包罗CPU,内部存款和储蓄器,硬盘

    关门文件的注意事项:

    打开一个文件包含两部分资源:操作系统级打开的文件 应用程序的变量。在操作完毕一个文件时,必须把与该文件的这两部分资源一个不落地回收,回收方法为:
    1、f.close() #回收操作系统级打开的文件
    2、del f #回收应用程序级的变量
    
    其中del f一定要发生在f.close()之后,否则就会导致操作系统打开的文件还没有关闭,白白占用资源,
    而python自动的垃圾回收机制决定了我们无需考虑del f,这就要求我们,在操作完毕文件后,一定要记住f.close()
    
    虽然我这么说,但是很多同学还是会很不要脸地忘记f.close(),对于这些不长脑子的同学,我们推荐傻瓜式操作方式:使用with关键字来帮我们管理上下文
    with open('a.txt','w') as f:
        pass
    
    with open('a.txt','r') as read_f,open('b.txt','w') as write_f:
        data=read_f.read()
        write_f.write(data)
    
    注意
    

    关闭文件的注意事项:

    新葡亰496net 1新葡亰496net 2

    打开一个文件包含两部分资源:操作系统级打开的文件 应用程序的变量。在操作完毕一个文件时,必须把与该文件的这两部分资源一个不落地回收,回收方法为:
    1、f.close() #回收操作系统级打开的文件
    2、del f #回收应用程序级的变量
    
    其中del f一定要发生在f.close()之后,否则就会导致操作系统打开的文件还没有关闭,白白占用资源,
    而python自动的垃圾回收机制决定了我们无需考虑del f,这就要求我们,在操作完毕文件后,一定要记住f.close()
    
    虽然我这么说,但是很多同学还是会很不要脸地忘记f.close(),对于这些不长脑子的同学,我们推荐傻瓜式操作方式:使用with关键字来帮我们管理上下文
    with open('a.txt','w') as f:
        pass
    
    with open('a.txt','r') as read_f,open('b.txt','w') as write_f:
        data=read_f.read()
        write_f.write(data)
    
    注意
    

    View Code

     

     

    文本操作基本流程

    Computer种类分为:Computer硬件,操作系统,应用程序三有个别。

    咱俩用python或任何语言编写的应用程序若想要把数据永世保存下来,必须要保存于硬盘中,那就提到到应用程序要操作硬件,深入人心,应用程序是不能够直接操作硬件的,那就用到了操作系统。操作系统把复杂的硬件操作封装成轻巧的接口给用户/应用程序使用,其汉语件就是操作系统提需求应用程序来操作硬盘虚拟概念,用户或应用程序通过操作文件,可以将和睦的多寡恒久保存下来。

    有了文本的定义,大家不需求再去思虑操作硬盘的内部原因,只要求关心操作文件的流程:

    #1. 打开文件,得到文件句柄并赋值给一个变量
    f=open('a.txt','r',encoding='utf-8') #默认打开模式就为r
    
    #2. 通过句柄对文件进行操作
    data=f.read()
    
    #3. 关闭文件
    f.close()
    

    3. 文件a1.txt内容:

    文件内容:
    name:apple price:10 amount:3 year:2012
    name:tesla price:100000 amount:1 year:2013
    
    通过代码,将其构建成这种数据类型:
    [{'name':'apple','price':10,'amount':3},
    {'name':'tesla','price':1000000,'amount':1}......]
    
    # 直接通过a模式创建题目所需要的a1文件
    # with open('a1.txt', encoding='utf-8', mode='a') as f1:
    #     f1.write('name:apple price:10 amount:3 year:2012n')
    #     f1.write('name:tesla price:100000 amount:1 year:2013')
    
    # 接下来的解题代码如下:
    lis = []
    dic = {}
    with open('a1.txt', encoding='utf-8', mode='r') as f2:
        for i in f2:
            # 第一次大循环按行转换成列表
            li = i.strip().split()
            for j in li:
                # 小循环里面通过分割':'得到一对键值对
                KeyVal = j.split(':')
                # 分别赋值给初始的空字典,完成小循环添加完毕
                dic.setdefault(KeyVal[0], KeyVal[1])
            # 第一行大循环时增添第一行对应的dic字典
            lis.append(dic)
            # 关键来了,再把字典给清空再进行第二行的大循环,不然小循环里会增添不上。
            dic = {}
    print(lis)
    

    绝大繁多CPU都有二种形式,即内核态与用户态。        

    二. 文件编码

    f=open(...)

    是由操作系统张开文件,那么一旦大家从没为open钦定编码,那么张开文件的默许编码很驾驭是操作系统说了算了

    操作系统会用自身的默许编码去开辟文件,在windows下是gbk,在linux下是utf-8。

    #这就用到了上节课讲的字符编码的知识:若要保证不乱码,文件以什么方式存的,就要以什么方式打开。
    f=open('a.txt','r',encoding='utf-8')
    

    二,文件编码

    f=open(...)是由操作系统张开文件,那么一旦我们尚无为open钦定编码,那么展开文件的私下认可编码很明朗是操作系统说了算了,操作系统会用本人的默许编码去开发文件,在windows下是gbk,在linux下是utf-8。

    #这就用到了上节课讲的字符编码的知识:若要保证不乱码,文件以什么方式存的,就要以什么方式打开。
    f=open('a.txt','r',encoding='utf-8')
    

     

    闭馆文件的注意事项:

    打开一个文件包含两部分资源:操作系统级打开的文件 应用程序的变量。在操作完毕一个文件时,必须把与该文件的这两部分资源一个不落地回收,回收方法为:
    1、f.close() #回收操作系统级打开的文件
    2、del f #回收应用程序级的变量
    
    其中del f一定要发生在f.close()之后,否则就会导致操作系统打开的文件还没有关闭,白白占用资源,
    而python自动的垃圾回收机制决定了我们无需考虑del f,这就要求我们,在操作完毕文件后,一定要记住f.close()
    
    虽然我这么说,但是很多同学还是会很不要脸地忘记f.close(),对于这些不长脑子的同学,我们推荐傻瓜式操作方式:使用with关键字来帮我们管理上下文
    with open('a.txt','w') as f:
        pass
    
    with open('a.txt','r') as read_f,open('b.txt','w') as write_f:
        data=read_f.read()
        write_f.write(data)
    

    4,文件a2.txt内容:

    文本内容:
    序号 部门 人数 平均年龄 备注
    1 python 30 26 单身狗
    2 Linux 26 30 没对象
    3 运营部 20 24 女生多
    经过代码,将其创设成这种数据类型:
    [{'序号':'1','部门':Python,'人数':30,'平均年龄':26,'备注':'光棍'},
    ......]

    li = []
    with open('a2.txt', encoding='utf-8', mode='r') as f1:
        key = f1.readline().strip().split()
        # 先读取第一行作为key键的列表元素
        # 此时光标己移到第2行开头,再进行后面同样是充当键值的行循环就简单多了
        print(key)
        for i in f1:
            print(i)
            val = i.strip().split()
            # 以key为基准,循环i次去进行zip函数两个列表合并成字典的操作就简单了
            dic = dict(zip(key, val))
            li.append(dic)
    print(li)
    
    每一步print出来的效果如下,可以更直观看到:
    
    ['序号', '部门', '人数', '平均年龄', '备注']
    
    1       python    30         26         单身狗
    
    2       Linux     26         30         没对象
    
    3       运营部     20         24         女生多
    
    [{'平均年龄': '26', '备注': '单身狗', '部门': 'python', '人数': '30', '序号': '1'}, 
     {'平均年龄': '30', '备注': '没对象', '部门': 'Linux', '人数': '26', '序号': '2'}, 
     {'平均年龄': '24', '备注': '女生多', '部门': '运营部', '人数': '20', '序号': '3'}]
    

    5,明天默写:正是第二题的代码(课上讲过)。

    ①当cpu处于根本状态时,运营的是操作系统,能调节硬件(能够获得具备cpu的指令集)     

    三. 文件的展开形式

    文件句柄 = open(‘文件路线’,‘形式’)

    #1. 打开文件的模式有(默认为文本模式):
    r ,只读模式【默认模式,文件必须存在,不存在则抛出异常】
    w,只写模式【不可读;不存在则创建;存在则清空内容】
    a, 只追加写模式【不可读;不存在则创建;存在则只追加内容】
    
    #2. 对于非文本文件,我们只能使用b模式,"b"表示以字节的方式操作(而所有文件也都是以字节的形式存储的,使用这种模式无需考虑文本文件的字符编码、图片文件的jgp格式、视频文件的avi格式)
    rb 
    wb
    ab
    注:以b方式打开时,读取到的内容是字节类型,写入时也需要提供字节类型,不能指定编码
    
    #3,‘ ’模式(就是增加了一个功能)
    r , 读写【可读,可写】
    w ,写读【可写,可读】
    a , 写读【可写,可读】
    
    #4,以bytes类型操作的读写,写读,写读模式
    r b, 读写【可读,可写】
    w b,写读【可写,可读】
    a b, 写读【可写,可读】
    

    三,文件的开发格局

    文本句柄 = open(‘文件路线’,‘情势’)

    #1. 打开文件的模式有(默认为文本模式):
    r ,只读模式【默认模式,文件必须存在,不存在则抛出异常】
    w,只写模式【不可读;不存在则创建;存在则清空内容】
    a, 只追加写模式【不可读;不存在则创建;存在则只追加内容】
    
    #2. 对于非文本文件,我们只能使用b模式,"b"表示以字节的方式操作(而所有文件也都是以字节的形式存储的,使用这种模式无需考虑文本文件的字符编码、图片文件的jgp格式、视频文件的avi格式)
    rb 
    wb
    ab
    注:以b方式打开时,读取到的内容是字节类型,写入时也需要提供字节类型,不能指定编码
    
    #3,‘ ’模式(就是增加了一个功能)
    r , 读写【可读,可写】
    w ,写读【可写,可读】
    a , 写读【可写,可读】
    
    #4,以bytes类型操作的读写,写读,写读模式
    r b, 读写【可读,可写】
    w b,写读【可写,可读】
    a b, 写读【可写,可读】
    

     

    文件编码

    f=open(...)是由操作系统展开文件,那么一旦我们从未为open钦赐编码,那么张开文件的暗中同意编码很通晓是操作系统说了算了,操作系统会用本身的私下认可编码去开采文件,在windows下是gbk,在linux下是utf-8。

    #这就用到了上节课讲的字符编码的知识:若要保证不乱码,文件以什么方式存的,就要以什么方式打开。
    f=open('a.txt','r',encoding='utf-8')
    

    ②当cpu处于用户太状态时,运维的是用户软件,无法说了算硬件(能够博得具备cpu的授命聚焦的三个子集,该子集不包含操作硬件的指令集)

    四. 文件操作方法

     四,文件操作方法。

    文件的张开形式

    文件句柄 = open(‘文件路径’,‘格局’)

    #1. 打开文件的模式有(默认为文本模式):
    r ,只读模式【默认模式,文件必须存在,不存在则抛出异常】
    w,只写模式【不可读;不存在则创建;存在则清空内容】
    a, 只追加写模式【不可读;不存在则创建;存在则只追加内容】
    
    #2. 对于非文本文件,我们只能使用b模式,"b"表示以字节的方式操作(而所有文件也都是以字节的形式存储的,使用这种模式无需考虑文本文件的字符编码、图片文件的jgp格式、视频文件的avi格式)
    rb 
    wb
    ab
    注:以b方式打开时,读取到的内容是字节类型,写入时也需要提供字节类型,不能指定编码
    
    #3,‘ ’模式(就是增加了一个功能)
    r , 读写【可读,可写】
    w ,写读【可写,可读】
    a , 写读【可写,可读】
    
    #4,以bytes类型操作的读写,写读,写读模式
    r b, 读写【可读,可写】
    w b,写读【可写,可读】
    a b, 写读【可写,可读】
    

    新葡亰496net 3 

    4.1常用操作方法

    read(3):

      1. 文本张开药格局为文本方式时,代表读取3个字符

      2. 文本张开情势为b情势时,代表读取3个字节

    任何的公文内光标移动都以以字节为单位的如:seek,tell,truncate

    注意:

      1. seek有二种运动格局0,1,2,当中1和2必须在b方式下进展,但随意哪一种格局,都以以bytes为单位活动的

      2. truncate是截断文件,所以文件的展开药情势必须可写,不过无法用w或w 等措施张开,因为那样直接清空文件了,所以truncate要在r 或a或a 等形式下测试效果。

    4.1常用操作方法。

    read(3):

      1. 文件展开药方式为文本形式时,代表读取3个字符

      2. 文件打开形式为b情势时,代表读取3个字节

    任何的公文内光标移动都以以字节为单位的如:seek,tell,truncate

    注意:

      1. seek有二种运动格局0,1,2,当中1和2必须在b情势下进展,但随意哪个种类形式,都以以bytes为单位活动的

      2. truncate是截断文件,所以文件的展开药格局必须可写,可是无法用w或w 等办法张开,因为那样直接清空文件了,所以truncate要在r 或a或a 等情势下测试效果。

    文本操作方法

    至于文件:

    4.2具备操作方法

    新葡亰496net 4新葡亰496net 5

    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

    新葡亰496net 6新葡亰496net 7

    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 'rn'.  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 'rn', 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.x

    4.2富有操作方法。

    新葡亰496net 8新葡亰496net 9

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

    新葡亰496net 10新葡亰496net 11

    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 'rn'.  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 'rn', 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.x

     

    常用操作方法

    read(3):
    
      1. 文件打开方式为文本模式时,代表读取3个字符
    
      2. 文件打开方式为b模式时,代表读取3个字节
    
    其余的文件内光标移动都是以字节为单位的如:seek,tell,truncate
    
    注意:
    
      1. seek有三种移动方式0,1,2,其中1和2必须在b模式下进行,但无论哪种模式,都是以bytes为单位移动的
    
      2. truncate是截断文件,所以文件的打开方式必须可写,但是不能用w或w 等方式打开,因为那样直接清空文件了,所以truncate要在r 或a或a 等模式下测试效果。
    
    • 文本能够积存不相同类型的音讯,一个文书能够涵盖文本,图片,录像,Computer程序等内容。
    • Computer上硬盘上有着的内容都以以文件的样式积攒。程序就是由一个要么多少个公文构成的。
    • 文件对象是python代码对Computer上海外国语高校部文件的重中之重接口。

    五. 文件的退换

    文件的多寡是存放在于硬盘上的,由此只设有覆盖、不存在修改这么一说,我们平日观望的退换文件,都以仿照出来的效应,具体的说有三种实现情势:

    艺术一:将硬盘存放的该公文的从头到尾的经过全方位加载到内部存款和储蓄器,在内存中是能够修改的,修改完结后,再由内部存款和储蓄器覆盖到硬盘(word,vim,nodpad 等编辑器)

    新葡亰496net 12新葡亰496net 13

    import os  # 调用系统模块
    
    with open('a.txt') as read_f,open('.a.txt.swap','w') as write_f:
        data=read_f.read() #全部读入内存,如果文件很大,会很卡
        data=data.replace('alex','SB') #在内存中完成修改
    
        write_f.write(data) #一次性写入新文件
    
    os.remove('a.txt')  #删除原文件
    os.rename('.a.txt.swap','a.txt')   #将新建的文件重命名为原文件
    

    方法一

    格局二:将硬盘存放的该文件的内容一行一行地读入内部存款和储蓄器,修改完结就写入新文件,最终用新文件覆盖源文件

    新葡亰496net 14新葡亰496net 15

    import os
    
    with open('a.txt') as read_f,open('.a.txt.swap','w') as write_f:
        for line in read_f:
            line=line.replace('alex','SB')
            write_f.write(line)
    
    os.remove('a.txt')
    os.rename('.a.txt.swap','a.txt') 
    

    方法二

    五,文件的改造。

    文件的数目是存放于硬盘上的,因此只设有覆盖、不设有修改这么一说,大家日常来看的改造文件,都以模拟出来的功效,具体的说有二种实现格局:

    艺术一:将硬盘存放的该公文的开始和结果全方位加载到内部存款和储蓄器,在内部存储器中是能够修改的,修改完成后,再由内部存款和储蓄器覆盖到硬盘(word,vim,nodpad 等编辑器)

    import os  # 调用系统模块
    
    with open('a.txt') as read_f,open('.a.txt.swap','w') as write_f:
        data=read_f.read() #全部读入内存,如果文件很大,会很卡
        data=data.replace('alex','SB') #在内存中完成修改
    
        write_f.write(data) #一次性写入新文件
    
    os.remove('a.txt')  #删除原文件
    os.rename('.a.txt.swap','a.txt')   #将新建的文件重命名为原文件
    

     

    格局二:将硬盘存放的该文件的内容一行一行地读入内部存款和储蓄器,修改达成就写入新文件,最终用新文件覆盖源文件

    import os
    
    with open('a.txt') as read_f,open('.a.txt.swap','w') as write_f:
        for line in read_f:
            line=line.replace('alex','SB')
            write_f.write(line)
    
    os.remove('a.txt')
    os.rename('.a.txt.swap','a.txt') 
    

     

    不无操作方法。

    新葡亰496net 16新葡亰496net 17

    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

    新葡亰496net 18新葡亰496net 19

    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 'rn'.  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 'rn', 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

    文件属性:

    六. 当日演习

    1. 文本a.txt内容:每一行内容分别为商品名字,价钱,个数。

    apple 10 3

    tesla 100000 1

    mac 3000 2

    lenovo 30000 3

    chicken 10 3

    通过代码,将其营形成这种数据类型:[{'name':'apple','price':10,'amount':3},{'name':'tesla','price':1000000,'amount':1}......] 并妄想出总价钱。

    2,有如下文件:


    alex是老男孩python发起人,制造人。

    alex其实是人妖。

    谁说alex是sb?

    你们真逗,alex再牛逼,也掩饰不住资深土冒的气度。


    将文件中有所的alex都替换来大写的SB。

    六,当日练习。

    1. 文本a.txt内容:每一行内容分别为物品名字,价钱,个数。

    apple 10 3

    tesla 100000 1

    mac 3000 2

    lenovo 30000 3

    chicken 10 3

    透过代码,将其构建成这种数据类型:[{'name':'apple','price':10,'amount':3},{'name':'tesla','price':1000000,'amount':1}......] 并企图出总价钱。

    2,有如下文件:


    alex是老男孩python发起人,创设人。

    alex其实是人妖。

    谁说alex是sb?

    你们真逗,alex再牛逼,也掩饰不住资深土冒的风姿。


    将文件中全体的alex都替换到大写的SB。

     

    文本的改换

    文件的数目是存放于硬盘上的,因此只设有覆盖、不设有修改这么一说,我们平日来看的改动文件,都以模拟出来的效果,具体的说有三种完成格局:

      名字

    方式一:

    将硬盘存放的该文件的内容全方位加载到内部存储器,在内部存款和储蓄器中是足以修改的,修改达成后,再由内部存款和储蓄器覆盖到硬盘(word,vim,nodpad 等编辑器)

    import os  # 调用系统模块
    
    with open('a.txt') as read_f,open('.a.txt.swap','w') as write_f:
        data=read_f.read() #全部读入内存,如果文件很大,会很卡
        data=data.replace('alex','SB') #在内存中完成修改
    
        write_f.write(data) #一次性写入新文件
    
    os.remove('a.txt')  #删除原文件
    os.rename('.a.txt.swap','a.txt')   #将新建的文件重命名为原文件
    

      类型(注脚文件数据类型,是图表,音乐,照旧文本)

    方式二:

    将硬盘存放的该文件的内容一行一行地读入内存,修改完结就写入新文件,最终用新文件覆盖源文件

    import os
    
    with open('a.txt') as read_f,open('.a.txt.swap','w') as write_f:
        for line in read_f:
            line=line.replace('alex','SB')
            write_f.write(line)
    
    os.remove('a.txt')
    os.rename('.a.txt.swap','a.txt') 
    

      地方(存款和储蓄在哪儿)

    当日演练

    1. 文件a.txt内容:每一行内容分别为物品名字,价钱,个数。

    apple 10 3

    tesla 100000 1

    mac 3000 2

    lenovo 30000 3

    chicken 10 3

    通过代码,将其创设成这种数据类型:[{'name':'apple','price':10,'amount':3},{'name':'tesla','price':1000000,'amount':1}......] 并总结出总价钱。

    2,有如下文件:


    alex是老男孩python发起人,创立人。

    alex其实是人妖。

    谁说alex是sb?

    你们真逗,alex再牛逼,也掩饰不住资深土冒的气质。


    将文件中装有的alex都替换到大写的SB。

      大小(文件中有微微字节)

    文件名:

      大部操作系统中(包括Windows),文件名中有部分用来提醒文件中含有怎么样项目标多少。文件名中家常便饭最少有一个点(.),点后边的局地提议了文件的品种。这一局地称作扩展名(extension)

    如:my_letter.txt中的增添名是.txt,代表“文本”,

      my_新葡亰496net:python之文件操作,文件操作以及序列化。letter.exe中,扩张名.exe,代表“可实践文件”

     文件基础用法提示:

    文件迭代器是最好的读取行工具
    内容是字符串,不是对象  
    close时通常选项,调用close会终止对外部文件的连接
    文件是缓冲的并且是可查找的

    有关文件路线难点:

      每一个文件都要存款和储蓄在某些地点,所以除了文件名以外,每个文件还有相应的职分,硬盘和任何存款和储蓄介质都社团为文件夹或目录。

      文件夹(folder)和目录(directorie)表示的是同同样东西,只是名字分化而已。文件夹或目录协会和涉及的措施叫做文件夹结构或目录结构。

      位于其余文件夹中的文件夹称为子文件夹(subfolder),假使用目录描述则成为子目录(subdirectory)

    新葡亰496net 20

     

    该文件路线:‪C:python36Toolsscripts__pycache__

    tips:斜线(和/)的不易利用,在路线名中那二者都领受,可是为了防止报错,最棒使用/,假诺利用偶然候会和后边字母形成转译符,如t,假如您非要使用,能够选拔\

    地方路线被称之为相对路线:从根目录开头,拔尖一流查找文件,直到找到文件。

         此外还应该有相对路线:在同样文件夹下,直接写文件名就能够。

    4.1操作文件流程:

    操作文件前务必的记住,文件以怎么样编码方式存款和储蓄,就要以什么编码格局张开,不然会很轻巧报错。

    #1. 打开文件,得到文件句柄并赋值给一个变量
    f=open('a.txt', mode = 'r', encoding='utf-8')   #默认打开模式就为r
    
    #2. 通过句柄对文件进行操作
    data=f.read()  # 读取文件内容
    data = f.readlines()  # 读取文件的所有行,直至文件末尾,包括每行换行字符n,输出的是一个列表
    data = f.readline()   # 一次只读取文件的一行,如果再在一个程序中使用它,python会记住当前位置,第二次使用会得到第二行 ,输出的是字符串
    data = f.read(n)  # 在r模式下,read(n)按照字符去读取。在rb模式下,read(n)按照字节去读取。
    循环读取:
    f = open('log.txt',encoding='utf-8')
    for i in f:
      print(i.strip())   # 每次读取一行,好处在于节省内存
    f.close()
    
    f.seek(0)   #如果使用了好几次readline,现在想退回到文件起始位置,可以使用该方法。其中括号里的数字是从文件起始位置算起的字节数
    #3. 关闭文件
    f.close()      #这个步骤很关键,可以帮助节省资源
    
    关闭文件注意事项:
    打开一个文件包含两部分资源:操作系统级打开的文件 应用程序的变量。在操作完毕一个文件时,必须把与该文件的这两部分资源一个不落地回收,回收方法为:
    
    1、f.close() #回收操作系统级打开的文件
    2、del f #回收应用程序级的变量
    其中del f一定要发生在f.close()之后,否则就会导致操作系统打开的文件还没有关闭,白白占用资源,
    而python自动的垃圾回收机制决定了我们无需考虑del f,这就要求我们,在操作完毕文件后,一定要记住f.close()
    
    
    with关键字管理上下文:
    
    #功能一:自动关闭文件句柄。
    #功能二:一次性操作多个文件句柄。
    
    with open('a.txt','w') as f: 
      pass 
    with open('a.txt','r') as read_f,open('b.txt','w') as write_f: 
      data=read_f.read() 
      write_f.write(data)
    

     4.2文件编码

    f=open(...)是由操作系统打开文件,那么如果我们没有为open指定编码,那么打开文件的默认编码很明显是操作系统说了算了,
    操作系统会用自己的默认编码去打开文件,在windows下是gbk,在linux下是utf-8。
    若要保证不乱码,文件以什么方式存的,就要以什么方式打开。
    f=open('a.txt','r',encoding='utf-8')
    

     4.3文本的展开情势

    打开主要分两种类型:
    文本文件:这些文件包含了文本,包括字母、数字、标点符号和一些特殊字符,如换行符。
    二进制文件:这些文件不包含文本,它们可能包含音乐、图片或其他类型的数据。这些文件中不包含文件,所以没有行,不存在换行符。
          (间接性说明不能对二进制文件使用readline()或者readliners())
           # 大多数情况下,若果需要使用二进制文件,就要通过pygame或者其他一些模块来加载文件
    
    #1. 打开文本文件模式有:
    
    • r, 只读形式【默许情势,文件必须存在,不设有则抛出非凡】
    • w, 只写格局【不可读;不存在则开创;存在则清空内容】
    • x, 只写格局【不可读;不存在则开创,存在则报错】
    • a, 追加情势【可读;不设有则成立;存在则只扩展内容】
    #2. 对于非文本文件(二进制文件),我们只能使用b模式,"b"表示以字节的方式操作
    (而所有文件也都是以字节的形式存储的,使用这种模式无需考虑文本文件的字符编码、图片文件的jgp格式、视频文件的avi格式)
    rb或r b,读写
    wb或w b,写读
    ab或a b,写读
    注:以b方式打开时,读取到的内容是字节类型,写入时也需要提供字节类型,不能指定编码
    
    #3,‘ ’模式(就是增加了一个功能)
    r , 先读,后追加。一定要先读后写
    w , 先写,后读(这个其实作用并不大,写完光标已经到最后,打印啥都没有,必须还需把光标移到前面才能读)
    a , 追加,再读(这个也一样)
    
    练习,利用b模式,编写一个cp工具,要求如下:
    既可以拷贝文本又可以拷贝视频,图片等文件
    
    1 # b模式
    2 f=open('1.jpg','rb')
    3 data=f.read()
    4 # print(data)
    5 f=open('2.jpg','wb')
    6 f.write(data)
    7 print(data) 
    

    一,用python制造二个新文件,内容是0到9的整数,各样数字占一行

    f = open('f.txt','w')
    for i in range(0,10):
        f.write(str(i) 'n')
    

    二,文件内容充实,从0到9的11个随机整数,每一个数字占用一行

    import random
    f = open('a.txt', 'a')
    for i in range(10):    #这一步作用在于让下面程序运行十次
        f.write(str(random.randint(0, 10)))
        f.write('n')    # 这一步其实也可以和上一步合并起来
    f.close()
    

    三、文件内容充实,从0到9的随机整数, 13个数字一行,共10行

    import random
    f = open('f.txt','a')
    for i in range(0,10):
        for i in range(0,10):
            f.write(str(random.randint(0,9)))
        f.write('n')
    f.close()
    

     逐行读取文件内容的三种方式:

    for line in open('f.txt'):
        print(line)
    
    or:
    f =open('f.txt','r')
    lines =f.readlines()  
    for i in lines:
        print(i)
    

    4.4文书操作方法

    4.4.0常用操作方法

     read(3):

      1. 文书张开药格局为文本情势时,代表读取3个字符

      2. 文书张开药形式为b方式时,代表读取3个字节

    任何的文本内光标移动都以以字节为单位的如:seek,tell,truncate

    注意:

      1. seek()是以bytes为单位活动的,依照字节调度光标地点

      2.tell()是按字节读取光标地点

      3. truncate是截断文件,所以文件的打开药方式必须可写,不过无法用w或w 等办法张开,因为这样间接清空文件了,所以truncate要在r 或a或a 等格局下测试效果。

    1 import time
    2 with open('test.txt','rb') as f:
    3     f.seek(0,2)
    4     while True:
    5         line=f.readline()
    6         if line:
    7             print(line.decode('utf-8'))
    8         else:
    9             time.sleep(0.2)
    

    4.4.1 序列化

      程序运营中,全体变量都以在内部存款和储蓄器里面,能够每天修退换量,但是只要程序甘休,变量所据有的内部存款和储蓄器就能够被操作系统全体回收。修改后的变量如果未有储存到磁盘上,下一次开垦又会开始化成原来的值。

      变量从内部存款和储蓄器中形成可存储或可传输的经过称之为类别化(python中称之为packling)。体系化之后,就足以把内容写入磁盘,或通过网络传输到别的磁盘上

    4.4.2 在文书中保留内容(文件的连串化)

    》》》》》》》》模块链接

    此地一般会用到pickle模块(它只好用于python,不一样的python版本之间或许也不相称)

    或许json模块(能够在分歧的编制程序语言之间传递对象,而且json表示出来正是叁个字符串,能够被有着语言替代)

    eval内置函数:

      该函数能够把字符串当作可实行代码运营,但是安全性较差,后面推荐应用hasattr映射

    x, y, z = 43, 44, 45
    S = 'splm'
    D = {'a': 1, 'b': 2}
    L = [1, 2, 3]
    
    F = open('file.txt', 'w')
    F.write(S   'n')
    F.write('%s%s%sn' % (x, y, x))
    F.write(str(L)   '$'   str(D)   'n')
    F.close()    
    # 通过以上步骤将内容写入文件中
    
    chars = open('file.txt')    # 打开文件
    line = chars.readline()    # 只读取一行
    line_two = chars.readline()
    line_three = chars.readline()
    print(line_three)
    parts = line_three.split('$')  
    print(parts)     #   ['[1, 2, 3]', "{'a': 1, 'b': 2}n"]
    print(eval(parts[1]))    #通过eval函数执行程序代码
    
    temp = [eval(i) for i in parts]
    print(temp)    #  [[1, 2, 3], {'a': 1, 'b': 2}]
    

     4.5 文件补充

    新葡亰496net 21

    新葡亰496net 22

    4.6文本的改变(利用os模块)

    列出当前目录下的持有目录:

    [x for x in os.listdir('.') if os.path.isdir(x)]

    要列出富有的 .py 文件,也只需一行代码:

    [x for x in os.listdir('.') if os.path.isfile(x) and os.path.splitext(x)[1]=='.py']

    4.7 文件删除和重命名

    文本的数码是存放在于硬盘上的,由此只存在覆盖、不存在修改这么一说,我们平时阅览标修改文件,都以模仿出来的意义,修改文件具体分为以下几步:

    1,将原文件读取到内存。
    2,在内存中进行修改,形成新的内容。
    3,将新的字符串写入新文件。
    4,将原文件删除。
    5,将新文件重命名成原文件。
    

    Python的os模块提供了帮你实行文书管理操作的法子,例如重命名和删除文件。要运用这几个模块,你必须先河入它,然后才得以调用相关的各个作用。

    重命名和删除文件:

    import os
    #重命名文件,旧文件名f.txt,新文件名file.txt
    os.rename('f.txt','file.txt')
    
    import os
    os.remove('stdout.txt') 
    

     

    方式一:将硬盘存放的该文件的内容总体加载到内部存款和储蓄器,在内部存款和储蓄器中是足以修改的,修改完结后,再由内部存款和储蓄器覆盖到硬盘(word,vim,nodpad 等编辑器)

    import os       # 调用系统模块
    
    with open('a.txt') as read_f, open('.a.txt.swap','w') as write_f:
      data=read_f.read()         #全部读入内存,如果文件很大,会很卡
      data=data.replace('alex','SB')      #在内存中完成修改
      write_f.write(data)      #一次性写入新文件
      os.remove('a.txt')           #删除原文件
      os.rename('.a.txt.swap','a.txt')      #将新建的文件重命名为原文件
    

     方式二:将硬盘存放的该公文的剧情一行一行地读入内部存款和储蓄器,修改实现就写入新文件,最后用新文件覆盖源文件

    import os
    
    with open('a.txt') as read_f, open('.a.txt.swap','w') as write_f:
      for line in read_f:
        line=line.replace('alex','SB')
        write_f.write(line)
    
    os.remove('a.txt')
    os.rename('.a.txt.swap','a.txt')
    

    例题:

    有如下文件:


    alex是老男孩python发起人,创立人。

    alex其实是人妖。

    谁说alex是sb?

    你们真逗,alex再牛逼,也掩饰不住资深土憋的气度。


    将文件中有所的alex都替换到大写的SB。

    新葡亰496net 23新葡亰496net 24

    import os
    with open('a.txt', mode='r', encoding='gbk') as f,
        open('b.txt', mode='w', encoding='gbk') as f1:
        for i in f:
            if 'alex' in i:
                a = i.replace('alex', 'SB')
                f1.write(a)
    os.remove('a.txt')
    os.rename('b.txt', 'a.txt')
    

    蒙面的妄想

    文本a.txt内容:每一行内容分别为物品名字,价钱,个数。

    apple 10 3

    tesla 100000 1

    mac 3000 2

    lenovo 30000 3

    chicken 10 3

    通过代码,将其创设成这种数据类型:[{'name':'apple','price':10,'amount':3},{'name':'tesla','price':1000000,'amount':1}......] 

    新葡亰496net 25新葡亰496net 26

    lis = []
    sums = 0
    f = open('a.txt', mode='r', encoding='utf-8')
    for i in f:
        s = i.strip().split(' ')
        a = dict([('name', s[0]), ('price', int(s[1])), ('amount', int(s[2]))])
        lis.append(a)
        sums  = int(s[1])*int(s[2])
    f.close()
    print(lis)
    

    low way

    新葡亰496net 27新葡亰496net 28

    with open('a.txt',encoding='utf-8') as f1:
        for i in f1:
            l2 = i.strip().split()           #l2 = [apple,10,3,2004]
            dic = {}
            for j in range(len(l2)):
                dic[name_list[j]] = l2[j]    # dic[name] = apple dic[price] = 10
            l1.append(dic)
    print(l1)
    

    爱慕编制程序观念

    文本a1.txt剧情:每一行内容分别为商品名字,价钱,个数。
    文件内容:

    name:apple price:10 amount:3 year:2012
    name:tesla price:100000 amount:1 year:2013

    透过代码,将其构建成这种数据类型:
    [{'name':'apple','price':10,'amount':3},
    {'name':'tesla','price':1000000,'amount':1}......]

    新葡亰496net 29新葡亰496net 30

    with open('a1.txt', mode='r', encoding='gbk') as f:
        for i in f:
            a = i.replace(':', ' ').strip()
            b = a.split(' ')
            dic = dict([(b[0], b[1]), (b[2], int(b[3])), (b[4],int(b[5]))])
            print(dic)
    

    low way

    新葡亰496net 31新葡亰496net 32

    l1 = []
    with open('a1.txt',encoding='utf-8') as f1:
        for i in f1:
            li = i.strip().split()
            dic = {}
            for j in li:
                l2 = j.strip().split(':')
                dic[l2[0]] = l2[1]
            l1.append(dic)
    print(l1)
    

    教员方法

    文本a2.txt剧情:每一行内容分别为货物名字,价钱,个数。

    文件内容:
    序号     部门      人数      平均年龄      备注
    1       python    30         26         单身狗
    2       Linux     26         30         没对象
    3       运营部     20         24         女生多
    因此代码,将其营造成这种数据类型:
    [{'序号':'1','部门':Python,'人数':30,'平均年龄':26,'备注':'光棍'},
    ......]

    新葡亰496net 33新葡亰496net 34

    d = []
    with open('a2.txt', mode='r', encoding='gbk')as f:
        s = f.readline()
        data = s.strip().split(' ')
        b = [x for x in data if x != '']
        for i in f:
            data1 = i.strip().split(' ')
            c = [x for x in data1 if x != '']
            dic = dict([(b[0], int(c[0])), (b[1], c[1]), (b[2], int(c[2])), (b[3], int(c[3])), (b[4], c[4])])
            d.append(dic)
    print(d)
    

    my idea

    新葡亰496net 35新葡亰496net 36

    d = []
    with open('a2.txt', mode='r', encoding='gbk')as f:
        lis = f.readline().strip().split()
        for i in f:
            b = i.strip().split()
            dic = dict([(lis[0], b[0]),(lis[1], b[1]),(lis[2], b[2]),(lis[3], b[3]),(lis[4], b[4])])
            d.append(dic)
    print(d)
    

    改建后的,看看和上边哪个地方不相同了

    新葡亰496net 37新葡亰496net 38

    lis = []
    with open('message.txt',encoding='gbk') as f:
        lis1 = f.readline().strip().split(',')
        for j in f:
            dic = {}
            lis2 = j.strip().split(',')
            for i in range(len(lis1)):
                dic[lis1[i]] = lis2[i]
            lis.append(dic)
        print(lis)
    

    自个儿为何想不到,利用len的章程

     

     

     

    本文由新葡亰496net发布于奥门新萄京娱乐场,转载请注明出处:新葡亰496net:python之文件操作,文件操作以及序

    关键词:

上一篇:新葡亰496net测试完整可运行,可商业运行

下一篇:没有了