• 零基础入门学习Python(28)--文件


    知识点

    Python中使用open(...)这个内置函数来打开文件,并返回文件对象

    open()函数参数说明

    open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)
    file: 传入文件名,如果只有文件名(不带路径),Python会在当前文件夹里去查找这个文件并打开
    mode: 文件打开模式,默认为r(读取)

    文件打开模式表

    模式 说明
    r 以只读模式打开(默认)
    w 以写入方式打开文件,如果不存在则创建,存在则覆盖
    x 以写入模式创建一个文件,如果文件已经存在,使用此模式打开将引发异常FileExistsError
    a 以写入模式打开,如果文件存在,则在末尾追加写入,不存在则创建
    b 以二进制模式打开文件
    t 以文本模式我打开(默认)
    + 可读写模式(可添加到其他模式中使用)
    U 通用换行符模式(已弃用)

    文件对象方法

    序号 方法 说明
    1 file.close() 关闭文件。关闭后文件不能再进行读写操作。
    2 file.flush() 刷新文件内部缓冲,直接把内部缓冲区的数据立刻写入文件, 而不是被动的等待输出缓冲区写入。
    3 file.fileno() 返回一个整型的文件描述符(file descriptor FD 整型), 可以用在如os模块的read方法等一些底层操作上。
    4 file.isatty() 如果文件连接到一个终端设备返回 True,否则返回 False。
    5 file.next() 返回文件下一行。
    6 file.read([size]) 从文件读取指定的字节数,如果未给定或为负则读取所有。
    7 file.readline([size]) 读取整行,包括 “ ” 字符。
    8 file.readlines([sizeint]) 读取所有行并返回列表,若给定sizeint>0,返回总和大约为sizeint字节的行, 实际读取值可能比 sizeint 较大, 因为需要填充缓冲区。
    9 file.seek(offset[, whence]) 设置文件当前位置
    10 file.tell() 返回文件当前位置。
    11 file.truncate([size]) 从文件的首行首字符开始截断,截断文件为 size 个字符,无 size 表示从当前位置截断;截断之后 V 后面的所有字符被删除,其中 Widnows 系统下的换行代表2个字符大小。
    12 file.write(str) 将字符串写入文件,没有返回值。
    13 file.writelines(sequence) 向文件写入一个序列字符串列表,如果需要换行则要自己加入每行的换行符。

    各方法详细说明

    close()

    概述:

    方法用于关闭一个已打开的文件。关闭后的文件不能再进行读写操作, 否则会触发 ValueError: I/O operation on closed file.错误。 close() 方法允许调用多次。

    当 file 对象,被引用到操作另外一个文件时,Python 会自动关闭之前的 file 对象。 使用 close() 方法关闭文件是一个好的习惯。

    示例:

    #!/usr/bin/python3
    
    #打开文件
    
    file1 = open('E:/test1.txt','wt')
    print('文件名为:',file1.name)
    
    #关闭文件
    file1.close()
    
    ====输出结果====
    文件名为: E:/test1.txt

    file.flush()

    概述
    flush() 方法是用来刷新缓冲区的,即将缓冲区中的数据立刻写入文件,同时清空缓冲区,不需要是被动的等待输出缓冲区写入。

    一般情况下,文件关闭后会自动刷新缓冲区,但有时你需要在关闭前刷新它,这时就可以使用 flush() 方法。

    示例

    #!/usr/bin/python3
    
    # 打开文件
    
    file1 = open('E:/test1.txt','wt')
    print('文件名为:',file1.name)
    
    # 刷新缓冲区
    file1.flush()
    
    #关闭文件
    file1.close()
    
    ====输出结果====
    文件名为: E:/test1.txt

    file.fileno()

    概述
    fileno() 方法返回一个整型的文件描述符(file descriptor FD 整型),可用于底层操作系统的 I/O 操作。

    示例

    #!/usr/bin/python3
    
    # 打开文件
    
    file1 = open('E:/test1.avi','wt')
    print('文件名为:',file1.name)
    
    fid = file1.fileno()
    print('文件描述符为: ', fid)
    
    #关闭文件
    file1.close()
    
    ====输出结果====
    文件名为: E:/test1.avi
    文件描述符为:  3
    

    file.isatty()

    概述
    isatty() 方法检测文件是否连接到一个终端设备,如果连接到一个终端设备返回 True,否则返回 False。

    示例

    #!/usr/bin/python3
    
    # 打开文件
    
    file1 = open('E:/test1.avi','wt')
    print('文件名为:',file1.name)
    
    ret = file1.isatty()
    print('返回值: ', ret)
    
    #关闭文件
    file1.close()
    
    ====输出结果====
    文件名为: E:/test1.avi
    返回值:  False

    file.next()

    概述
    next(iterator[,default])

    Python 3 中的 File 对象不支持 next() 方法。 Python 3 的内置函数 next() 通过迭代器调用 __next__()方法返回下一项。 在循环中,next()方法会在每次循环中调用,该方法返回文件的下一行,如果到达结尾(EOF),则触发StopIteration

    示例

    #!/usr/bin/python3
    
    # 打开文件
    
    file1 = open('E:/test.txt','r')
    print('文件名为:',file1.name)
    
    for each in range(1,7):
        line = next(file1)
        print("第 %d 行 - %s" % (each, line))
    
    #关闭文件
    file1.close()
    
    ===输出结果===
    Traceback (most recent call last):
      File "D:/untitled/Python_learn/File_Test.py", line 9, in <module>
        line = next(file1)
    StopIteration
    文件名为: E:/test.txt
    第 1 行 - 这是第一行
    
    第 2 行 - 这是第二行
    
    第 3 行 - 这是第三行
    
    第 4 行 - 这是第四行
    
    第 5 行 - 这是第五行
    
    ===输出结果===
    文件名为: E:/test.txt
    读取的字符串: 这是第一行
    这是第二

    file.read([size])

    概述
    read() 方法用于从文件读取指定的字节数,如果未给定或为负则读取所有。

    示例

    #!/usr/bin/python3
    
    # 打开文件
    
    file1 = open('E:/test.txt','r')
    print('文件名为:',file1.name)
    
    line = file1.read(10)
    print("读取的字符串: %s" % (line))
    
    #关闭文件
    file1.close()
    

    file.readline([size])

    概述
    readline() 方法用于从文件读取整行,包括 “ ” 字符。如果指定了一个非负数的参数,则返回指定大小的字节数,包括 “ ” 字符。

    示例

    text.txt文件内容:
    1:https://blog.csdn.net/wanbin6470398/
    2:https://blog.csdn.net/wanbin6470398/
    3:https://blog.csdn.net/wanbin6470398/
    4:https://blog.csdn.net/wanbin6470398/
    5:https://blog.csdn.net/wanbin6470398/
    
    
    #!/usr/bin/python3
    
    # 打开文件
    
    file1 = open('E:/test.txt','r')
    print('文件名为:',file1.name)
    
    line = file1.readline()
    print("读取第一行: %s" % (line))
    
    line = file1.readline()
    print("读取第二行: %s" % (line))
    
    line = file1.readline()
    print("读取第三行: %s" % (line))
    
    line = file1.readline(7)
    print("读取的字符串: %s" % (line))
    
    
    #关闭文件
    file1.close()
    
    
    ===输出结果===
    文件名为: E:/test.txt
    读取第一行: 1:https://blog.csdn.net/wanbin6470398/
    
    读取第二行: 2:https://blog.csdn.net/wanbin6470398/
    
    读取第三行: 3:https://blog.csdn.net/wanbin6470398/
    
    读取的字符串: 4:https
    

    file.readlines([sizeint])

    概述
    readlines() 方法用于读取所有行(直到结束符 EOF)并返回列表,该列表可以由 Python 的 for… in … 结构进行处理。 如果碰到结束符 EOF 则返回空字符串。

    如果碰到结束符 EOF 则返回空字符串。

    示例

    #!/usr/bin/python3
    
    # 打开文件
    
    file1 = open('E:/test.txt','r')
    print('文件名为:',file1.name)
    
    line = file1.readlines()
    print("读取的数据: %s" % (line))
    
    for each  in line:                 #依次读取每行
        each = each.strip()            #去掉每行头尾空白
        print("处理的数据为:%s" % each)
    
    #关闭文件
    file1.close()
    
    ===输出结果===
    读取的数据: ['1:https://blog.csdn.net/wanbin6470398/
    ', '2:https://blog.csdn.net/wanbin6470398/
    ', '3:https://blog.csdn.net/wanbin6470398/
    ', '4:https://blog.csdn.net/wanbin6470398/
    ', '5:https://blog.csdn.net/wanbin6470398/
    ']
    处理的数据为:1:https://blog.csdn.net/wanbin6470398/
    处理的数据为:2:https://blog.csdn.net/wanbin6470398/
    处理的数据为:3:https://blog.csdn.net/wanbin6470398/
    处理的数据为:4:https://blog.csdn.net/wanbin6470398/
    处理的数据为:5:https://blog.csdn.net/wanbin6470398/
    

    file.seek(offset[, whence])

    概述
    seek() 方法用于移动文件读取指针到指定位置。

    参数
    offset – 开始的偏移量,也就是代表需要移动偏移的字节数

    whence:可选,默认值为 0。给offset参数一个定义,表示要从哪个位置开始偏移;0代表从文件开头开始算起,1代表从当前位置开始算起,2代表从文件末尾算起。

    示例

    #!/usr/bin/python3
    
    # 打开文件
    
    file1 = open('E:/test.txt','r')
    print('文件名为:',file1.name)
    
    line = file1.readline()
    print("读取的数据: %s" % (line))
    
    #重新设置文件读取指针到开头
    file1.seek(0)
    line = file1.readline()
    print("读取的数据: %s" % (line))
    
    #关闭文件
    file1.close()
    
    ===输出结果===
    文件名为: E:/test.txt
    读取的数据: 1:https://blog.csdn.net/wanbin6470398/
    
    读取的数据: 1:https://blog.csdn.net/wanbin6470398/
    

    file.tell()

    概述
    tell() 方法返回文件的当前位置,即文件指针当前位置。

    示例

    #!/usr/bin/python3
    
    # 打开文件
    
    file1 = open('E:/test.txt','r')
    print('文件名为:',file1.name)
    
    line = file1.readline()
    print("读取的数据: %s" % (line))
    
    #获取当前位置
    pos = file1.tell()
    print("当前位置: %d" % pos)
    
    #关闭文件
    file1.close()
    
    ===输出结果===
    文件名为: E:/test.txt
    读取的数据: 1:https://blog.csdn.net/wanbin6470398/
    
    当前位置: 40
    

    file.truncate([size])

    概述
    truncate() 方法用于从文件的首行首字符开始截断,截断文件为 size 个字符,无 size 表示从当前位置截断;截断之后 V 后面的所有字符被删除,其中 Widnows 系统下的换行代表2个字符大小。

    示例

    #!/usr/bin/python3
    
    # 打开文件
    
    file1 = open('E:/test.txt','r+')
    print('文件名为:',file1.name)
    
    print('读取行:%s' % file1.readline())
    
    file1.truncate()
    print('读取行:%s' % file1.readlines())
    
    #关闭文件
    file1.close()
    
    ===输出结果===
    文件名为: E:/test.txt
    读取行:1:https://blog.csdn.net/wanbin6470398/
    
    读取行:['2:https://blog.csdn.net/wanbin6470398/
    ', '3:https://blog.csdn.net/wanbin6470398/
    ', '4:https://blog.csdn.net/wanbin6470398/
    ', '5:https://blog.csdn.net/wanbin6470398/']
    

    file.write(str)

    概述
    write() 方法用于向文件中写入指定字符串。

    在文件关闭前或缓冲区刷新前,字符串内容存储在缓冲区中,这时你在文件中是看不到写入的内容的。

    示例

    #!/usr/bin/python3
    
    # 打开文件
    
    file1 = open('E:/test.txt','r+',encoding='utf-8')
    print('文件名为:',file1.name)
    
    #在文件末尾写入一行
    file1.seek(0,2)
    file1.write('
    6:https://blog.csdn.net/wanbin6470398/')
    print(file1)
    #读取文件所有内容
    file1.seek(0,0)
    for index in range(1,7):
        line = next(file1)
        print("文件行号 %d - %s" % (index, line))
    
    #关闭文件
    file1.close()
    
    ===输出结果===
    文件名为: E:/test.txt
    <_io.TextIOWrapper name='E:/test.txt' mode='r+' encoding='utf-8'>
    文件行号 1 - 1:https://blog.csdn.net/wanbin6470398/
    
    文件行号 2 - 2:https://blog.csdn.net/wanbin6470398/
    
    文件行号 3 - 3:https://blog.csdn.net/wanbin6470398/
    
    文件行号 4 - 4:https://blog.csdn.net/wanbin6470398/
    
    文件行号 5 - 5:https://blog.csdn.net/wanbin6470398/
    
    文件行号 6 - 6:https://blog.csdn.net/wanbin6470398/

    file.writelines(sequence)

    概述
    writelines() 方法用于向文件中写入一序列的字符串。

    这一序列字符串可以是由迭代对象产生的,如一个字符串列表。

    换行需要制定换行符 。
    示例

    #!/usr/bin/python3
    
    # 打开文件
    
    file1 = open('E:/test.txt','w+',encoding='utf-8')
    print('文件名为:',file1.name)
    
    seq = ['csdn1
    ','csdn2
    ','csdn3
    ']
    file1.writelines(seq)
    
    #刷新缓冲区,把数据保存到磁盘
    file1.flush()
    
    #定位到文件开头位置
    file1.seek(0)
    print('文件内容:%s' % file1.read())
    
    #关闭文件
    file1.close()
    
    ===输出结果===
    文件名为: E:/test.txt
    文件内容:csdn1
    csdn2
    csdn3
    

    课后习题

  • 相关阅读:
    uniapp入门
    第一章、javascript高级
    Python绘制冰墩墩
    PyCharm快捷键大全
    关闭win10自动更新(详细步骤)
    神经网络与深度学习中文实战版电子书
    傅里叶变换、傅里叶级数——超详细讲解(史上最全)
    Python3基于PyMySQL封装的常用操作基础类库
    PHP根据二维数组的某个键去重
    PHP超简单生成唯一数字ID的方法
  • 原文地址:https://www.cnblogs.com/wanbin/p/9514671.html
Copyright © 2020-2023  润新知