zoukankan      html  css  js  c++  java
  • Python的文件操作

    读操作

    file = open('测试文件',mode='r',encoding='utf-8')
    print(file.read())

    写操作

    file = open('测试文件',mode='w',encoding='utf-8')
    file.write('	测试内容')                    # 这里的写入操作都会先将内容清空,再重新进行写入;并且支持转义字符的使用
    file.close()

    追加操作

    file = open('测试文件',mode='a',encoding='utf-8')
    file.write('
    	测试内容2')                 # 这里的写入操作并不会清空内容,并且同样支持转义符的使用
    file.close( )

    读写操作

    file = open('测试文件',mode='r+',encoding='utf-8')
    print(file.read())                          # read会从按照最小字符内容光标位置进行查看
    file.write('
    测试内容3')                   #  这里的写入操作并不会清空内容,但是不支持转义字符的使用
    file.close()

    写读操作

    file = open('测试文件',mode='w+',encoding='utf-8')
    file.write('
    测试内容4')                    # 这里会先覆盖原有内容再进行写入操作,支持转义字符的使用
    print(file.read())                         # 这里并不会打印任何内容,因为写入之后光标已经到了结尾
    file.close()

    追加写入

    file = open('测试文件', mode='a+', encoding='utf-8')
    file.write('
    测试内容5')                   #  这里的写入操作并不会清空内容,但是不支持转义字符的使用
    file.read()                            # 这里并不会打印任何内容,因为写入之后光标已经到了结尾
    file.close()

    调节光标位置

    file = open('测试文件', mode='w+', encoding='utf-8')
    file.write('测试内容7')
    file.seek(0)                              # seek方法是按照字节进行偏移
    print(file.read())

    指定光标内容打印

    file = open('测试文件', mode='w+', encoding='utf-8')
    file.write('测试内容8')
    file.seek(0)
    print(file.read(4))                          #从光标位置开始打印后面4个字符,切记这里是字符,并不是字节,即最小可视单位

    获取当前光标位置,主应用于断点续传

    file = open('测试文件', mode='w+', encoding='utf-8')
    file.write('测试内容8')
    file.seek(0)
    tell = file.tell()                          # 获取光标位置
    print(tell)

    判断文件权限

    s=open("t1.txt",mode="r+",encoding="utf-8")
    print(s.readable())
    print(s.writable())
    s.close()

    自动关闭文件句柄

    with open('测试文件', mode='w+', encoding='utf-8') as file:
        file.write('测试内容9')
        file.seek(0)
        print(file.read())

    以行为单位的读取

    with open('测试文件', mode='r', encoding='utf-8') as file:
        print(file.readline())                      # read方法会先将整个文件缓存到内存中,再进行操作

    每一行当成列表中的一个元素,添加到list中

    with open('测试文件', mode='w+', encoding='utf-8') as file:
        file.write('测试内容10
    测试内容11')
        file.seek(0)
        print(file.readlines())                         # 连带换行符都一并加载出来

    文本内容的剪切

    with open('测试文件', mode='r+', encoding='utf-8') as file:
        file.truncate(2)                                # 仅保留第一行前两个字节

    文件的重命名及删除

    import os
    os.rename('用户文件','用户文件1')       # 重命名文件
    os.remove('用户文件1')                  # 删除文件

    注意事项

    • 文件本身是无法修改的
    • 文件的默认操作是'读取'
    • 文件只能通过重命名的方式修改文件内容
  • 相关阅读:
    【软件测试】软件缺陷粗浅认识及白盒测试举例
    【软件测试】等价类划分
    【软件测试】对本门课程粗浅理解
    阿里云服务器本地ping超时,远程可以正常ping通
    不忘初心
    开源框架、控件、组件、插件记录
    Flex中窗口可随意拖拽功能实现
    初探数据类型相关问题
    [TSCTF-J 2021] 解题报告
    指针
  • 原文地址:https://www.cnblogs.com/guge-94/p/10406613.html
Copyright © 2011-2022 走看看