zoukankan      html  css  js  c++  java
  • 文件操作模式

    一:基本概念

    打开文件的模式有三种纯净模式:r(默认的)w a

    大前提:tb模式均不能单独使用,必须与纯净模式结合使用

    t文本模式:

        1、读写文件都是以字符串为单位的

        2、只能针对文本文件

        3、必须指定encoding参数

    b二进制模式:

        1、读写文件都是以bytes/二进制为单位的

        2、可以针对所有文件

        3、一定不能指定encoding参数

    二:打开文件模式详解

    1、r只读模式:在文件不存在时则报错,文件存在文件内指针直接跳到文件开头

     

    用户认证功能

    inp_name = input('请输入你的名字:').strip()

    inp_pwd = input('请输入你的密码:').strip()

    with open(r'db.txt',mode = 'rt',encoding = 'utf-8')as f:

        for line in f:

            u,p = line .strip(' ').split(':')

            if inp_name == u and inp_pwd == p:

                print('登录成功')

                break

        else:

            print('账号名或者密码错误')

    w只写模式:在文件不存在时会创建空文档,文件存在会清空文件,文件指针跑到文件开头

     

    注册功能:

    name = input('username:').strip()

    pwd = input('password:').strip()

    with open('db1.txt',mode='at',encoding='utf-8')as f:

        info='%s:%s '%(name,pwd)

        f.write(info)

    3、a只追加写模式:在文件不存在时会创建空文档,文件存在会将文件指针直接移动到文件末尾

     

    r+ w+ a+ :可读可写 ,不会改变

    b:读写都是以二进制为单位

    拷贝工具

    src_file = input('源文件路径:').strip()

    dst_file = input('目标文件路径:').strip()

    with open (r'%s'%src_file,mode='rb')as read_f,open(r'%s'%dst_file,mode='wb')as write_f:

        for line in read_f:

        write_f.write(line)

  • 相关阅读:
    Educational Codeforces Round 104 (Rated for Div. 2) A B C D E
    Codeforces Round #701 (Div. 2) A B C D
    Codeforces Round #700 (Div. 2) A B C D1
    记录一次Boot整合Batch框架无法连接达梦数据库的问题
    关于Java中的volatile关键字的总结,适合了解不太多的人
    写个日志切面追踪,可以更直接查看项目执行的各种信息打印。
    sqlServer实现group by 之后 聚合操作之拼接结果
    SQL CURSOR 游标
    SQL case when
    Redis版本
  • 原文地址:https://www.cnblogs.com/xiamenghan/p/9683339.html
Copyright © 2011-2022 走看看