• python基础---文件基本操作(20)


    1、打开文件

    Windows路径分隔符问题

    • 解决方案一:推荐

      open(r'C:\a\ad\c.txt')
      
      • 1
    • 解决方案二:

       open('C:/a/ad/c.txt')
      
      • 1

    Linux环境下

    open('/a/ad/c.txt')
    
    • 1

    2、如何用文件:open()

    控制文件读写内容的模式:t和b
    强调:t和b不能单独使用,必须跟r/w/a连用
    t文本(默认的模式)

    • 读写都以str(unicode)为单位
    • 文本文件
    • 必须指定encoding=‘utf-8’
    f = open(r'a.txt', mode='rt')  # f的值是一种变量,占用的是应用程序的内存空间
     print(f)
    
    • 1
    • 2

    3、操作文件

    读/写文件,应用程序对文件的读写请求都是在向操作系统发送系统调用,然后由操作系统控制硬盘把输入读入内存、或者写入硬盘

    f = open(r'a.txt', mode='rt')
    res = f.read()
    print(res)
    
    • 1
    • 2
    • 3

    4、关闭文件

    f.close()  # 回收操作系统资源
    del f  # 回收应用程序资源
    
    • 1
    • 2

    5、with上下文管理

    文件对象又称文件句柄

    • 方式一:一次打开一个文件

      with open(r'a.txt', mode='rt') as f1:
          res = f1.read()
          print(res)
      
      • 1
      • 2
      • 3
    • 方式二:一次打开两个文件或多个文件

      with open('a.txt') as f1,  open('b.txt') as f2:
          res1 = f1.read()
          res2 = f2.read()
          print(res2)
          print(res1)
      
      • 1
      • 2
      • 3
      • 4
      • 5

    6、指定字符编码

    没有指定encoding参数操作系统会使用自己默认的编码

    • Linux系统默认utf-8
    • windows系统默认gbk
    '''
    如何用文件:open()
        控制文件读写内容的模式:t和b
            强调:t和b不能单独使用,必须跟r/w/a连用
                t文本(默认的模式)
                    1、读写都以str(unicode)为单位
                    2、文本文件
                    3、必须指定encoding='utf-8'
    '''
    with open('a.txt', mode='rt',encoding='utf-8') as f:
        res = f.read()
        print(res, type(res))
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    7、以t模式为基础进行内存操作

    7.1 r模式(默认的操作模式)

    r(默认的操作模式):只读模式,当文件不存在时,当文件存在时文件指针跳到开始位置

    with open('a.txt', mode='rt', encoding='utf-8') as f:
        print('第一次读'.center(50,'*'))
        res = f.read()  # 把所有内容从硬盘读入内存
        print(res)
    
        print('第二次读'.center(50,'*'))
        res = f.read()  # 把所有内容从硬盘读入内存
        print(res)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    案例:从一个user.txt文件中读出来,比对与用户输入的是否一致

    • 方式一:一次读一行
      inp_usrname = input('your name:').strip()
      inp_password = input('your password:').strip()
      
      # 验证
      with open('user.txt', mode='rt',encoding='utf-8') as f:
          for line in f:
              username,password = line.strip('\n').split(':')
              if inp_password == password and inp_usrname == username:
                  print('login successful')
                  break
          else:
              print('username or password error')
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
      • 12
    • 方式二:把文件里的内容都读出来
      inp_usrname = input('your name:').strip()
      inp_password = input('your password:').strip()
      
      with open('user.txt', mode='rt',encoding='utf-8') as f:
          res = f.read()
          username, password = res.split(':')
      if inp_password == password and inp_usrname == username:
          print('login successful')
      else:
          print('username or password error')
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10

    7.2 w模式

    w:只写模式,当文件不存在时会创建空文件,当文件存在时会清空文件,指针位于开始位置

    with open('d.txt',mode='wt', encoding='utf-8') as f:
        # f.read()  # 不可读
        f.write('哈哈哈\n')
    
    
    • 1
    • 2
    • 3
    • 4
    • 强调1:在以w模式打开文件没有关闭的情况下,连续写入,新写的内容总是跟在旧的之后

      with open('d.txt',mode='wt', encoding='utf-8') as f:
          f.write('哈哈哈1\n')
          f.write('哈哈哈2\n')
          f.write('哈哈哈3\n')
          f.write('哈哈哈4\n')
      
      • 1
      • 2
      • 3
      • 4
      • 5
    • 强调2:如果重新以w模式打开文件,则会清空文件内容

    with open('d.txt',mode='wt', encoding='utf-8') as f:
        f.write('哈哈哈1\n')
    with open('d.txt', mode='wt', encoding='utf-8') as f:
        f.write('哈哈哈2\n')
    with open('d.txt', mode='wt', encoding='utf-8') as f:
        f.write('哈哈哈3\n')
        f.write('哈哈哈4\n')
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    案例:w模式用来创建全新的文件
    文件的copy工具

    • 方式一:一次性拷贝内容
    src_file = input('源文件路径:').strip()
    dst_file = input('新文件路径:').strip()
    with open(r'{}'.format(src_file), mode='rt', encoding='utf-8') as f1,\
        open(r'{}'.format(dst_file), mode='wt', encoding='utf-8') as f2:
        res = f1.read()
        f2.write(res)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 方式二:按行拷贝内容
    src_file = input('源文件路径:').strip()
    dst_file = input('新文件路径:').strip()
    with open(r'{}'.format(src_file), mode='rt', encoding='utf-8') as f1,\
        open(r'{}'.format(dst_file), mode='wt', encoding='utf-8') as f2:
        for line in f1:
           f2.write(line)  
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    7.3 a模式

    a:只追加写,在文件不存在时会创建空文档,在文件存在时文件指针会直接跳到末尾

    with open('e.txt', mode='at', encoding='utf-8') as f:
        # f.read()  # 报错 不能读
        f.write('你好!\n')
        f.write('我是!\n')
        f.write('男人!\n')
    
    • 1
    • 2
    • 3
    • 4
    • 5

    案例:a模式用来在原有的文件内存的基础上写入新的内容,比如记录日志,注册
    注册功能:

    name = input("用户名:")
    pwd = input("密码:")
    with open('db.txt', mode='at', encoding='utf-8') as f:
        f.write('{}:{}\n'.format(name,pwd))
    
    
    • 1
    • 2
    • 3
    • 4
    • 5

    7.4 w模式与a模式的异同

    • 相同点:在打开的文件不关闭的情况下,连续的写入,新写的内容总会跟在前写的内容之后
    • 不同点:以a模式重新打开文件,不会清空原文件内容,会将文件指针直接移动到文件末尾,在末尾写入新内容

    7.5 +模式

    了解 :+不能单独使用,必须配合r、w、a

    with open('f.txt', mode='rt+', encoding='utf-8') as f:
        print(f.read())
        f.write('牛逼')
    
    with open('f.txt', mode='wt+', encoding='utf-8') as f:
        f.write('111\n')
        f.write('牛逼')
        print(f.read())
    
    with open('f.txt', mode='a+t', encoding='utf-8') as f:
        f.write('111\n')
        f.write('牛逼')
        print(f.read())
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
  • 相关阅读:
    将Java项目Jar包制作成Docker镜像
    小程序环境切换自定义组件
    一篇玩转mybatis-plus框架的详细讲解(入门必备)
    Sleuth+Zipkin 链路追踪
    工具方法合集-utils.js
    实验四、零比特插入《计算机网络》
    QT Day5思维导图
    JAVA应用服务器如何快速定位CPU问题
    傻白入门芯片设计,典型的2D/2D+/2.5D/3D封装技术(六)
    安装njnx --chatGPT
  • 原文地址:https://blog.csdn.net/qq_43707174/article/details/125879534