• python全栈闯关--8-文件操作


    1、打开文件open

    # 1、直接打开
    open('account', mode='w', encoding='utf-8')
    # 2、打开赋值给一个句柄
    f = open('account', mode='r', encoding='utf-8')
    f.close()
    # 3、使用with打开,好处是可以不使用close
    with open("account", mode='r', encoding='utf-8') as f1:
        pass

     文件可以是相对路径,也可以是绝对路径

    2、文件读取模式

    读r、r+、rb、r+b

    直接读取:

    f = open('account', mode='r', encoding='utf-8')
    print(f.read())
    f.close()

    按照字符读取:

    f = open('account', mode='r', encoding='utf-8')
    print(f.read(3))  # 读取字符读取,读取3个字符b
    f.close()

    使用rb模式读取

    f = open('account', mode='rb')  # 按照bytes读取,不需要指定字符集编码
    print(f.read())  # 执行结果为bytes类型
    f.seek(0)  # 跳到行首
    print(f.read().decode('utf-8'))  # bytes转换为utf-8 使用decode
    f.close()

    rb模式读取到结果为bytes格式

    bytes准换为字符串decode('格式')

    字符串转换成bytes使用encode('格式'),如果是英文,可以使用b'berr'方式转换,包含中午必须使用encode

     

    f = open('account', mode='r+', encoding='utf-8')
    print(f.read())
    f.write('this is bee honey')  # 先读,后写。读取到哪个位置,在哪个位置继续写
    f.close()
    
    f = open('account', mode='r+b')
    print(f.read().decode('utf-8'))
    f.write("write test
    ".encode('utf-8'))  # 如果不进行编码,会报错:TypeError: a bytes-like object is required, not 'str'
    f.writelines(['this is bee honey'.encode('utf-8'),
                  '
    second line'.encode('utf-8')])
    f.close()

     

     

    读w、wb、w+、w+b

    w模式

    f = open('account', mode='w', encoding='utf-8')  # 写模式都是删除后,重新写入,不会在原有基础上添加
    f.write('honey bee 
    ')
    f.write(" bear big !
    ")
    f.write("beear two!")
    f.close()

    wb模式

    f = open('account', mode='wb')  # 写模式都是删除后,重新写入,不会在原有基础上添加
    f.write('honey bee 
    '.encode('utf-8'))  # 需要写入的为bytes类型,否则报错
    f.write(b" bear big !
    ")  # b转换成bytes模式
    f.close()

    w+

    f = open('account', mode='w+', encoding='utf-8')  # 写模式都是删除后,重新写入,不会在原有基础上添加
    f.write('honey bee 
    ')  
    f.write(" bear big !")  
    f.seek(0)  # 指向文件开头,从头读取文件
    print(f.read())
    f.close()

    w+和r+都是同时读和同时写,r+先读后写,不覆盖原始文件。w+直接删除原文件后,才进行写入,导致w+模式不常用,一般使用r+模式

    f = open('account', mode='w+b')  # 写模式都是删除后,重新写入,不会在原有基础上添加
    print(f.read())
    f.write('honey bee 
    '.encode('utf-8'))
    f.write(" bear big !".encode('utf-8'))
    f.seek(0)  # 指向文件开头,从头读取文件
    print(f.read())
    f.close()

    追加 a、a+、ab、a+b

    a模式,只能在文件结尾追加,但是不能读取

    f = open('account', mode='a')  # 追加模式,文件结尾直接追加
    # 只能写,不能读取
    f.write('honey bee 
    ')
    f.write(" bear big !")
    f.close()

    a+模式,可以读取,也可以追加

    f = open('account', mode='a+')
    # f.read()
    f.write('honey bee 
    ')
    f.write(" bear big !")
    f.seek(0)
    print(f.read())
    f.close()

      ab模式,按照bytes型追加,只能追加,不能读取

    f = open('account', mode='ab')
    # f.read()
    f.write('honey bee 
    '.encode('utf-8'))
    f.write(" bear big !".encode('utf-8'))
    f.close()

    a+b模式,可以按照bytes追加,同时可以使用seek调整位置后,读取,写入

    f = open('account', mode='a+b')
    f.read()
    f.write('honey bee 
    '.encode('utf-8'))
    f.write(" bear big !".encode('utf-8'))
    f.seek(0)
    print(f.read())
    f.close()

    with模式,使用with模式打开文件,结束可以不必使用close函数

    with open('account', 'r+', encoding='utf-8') as f:
        content = f.read()
        print(content)

    练习:模拟注册、登录

    username = input("请输入你的用户名:")
    userpasswd = input("请输入你的密码:")
    
    with open('account', 'w', encoding='utf-8') as f:
        f.write("{}
    {}".format(username, userpasswd))
    
    print('注册成功!')
    
    lis = []
    try_count = 0
    
    while try_count < 3:
        in_uname = input("请输入你的用户名:")
        in_pwd = input("请输入你的密码:")
        with open('account', encoding='utf-8') as f1:
            for line in f1:
                lis.append(line)
        if in_uname == lis[0].strip() and in_pwd == lis[1].strip():
            print("登录成功!")
            break
        else:
            print("账户或者密码错误!")
            try_count += 1

    3、修改文件

    with open("account",mode='r',encoding='utf-8') as f1,open("account.bak",mode='w',encoding='utf-8') as f2:
        for i in f1:
            if "bear" in i:
                i = i.replace('bear', 'big two')
            f2.write(i)
    import os
    os.remove("account")
    os.rename("account.bak", "account")
  • 相关阅读:
    python 发邮件乱码
    膳魔师杯使用注意事项
    了解指针,分分钟的事情 C++筆記--指針
    海淘攻略
    【转】Cocos2dx.3x入门三部曲
    在Windows7上搭建Cocos2d-x 3.2alpha0开发环境
    黑苹果 MAC OS X 10.10.2 安装流程
    Linux 下如何查找木马并处理
    js如何判断访问是来自搜索引擎(蜘蛛人)还是直接访问
    泰*网 Centos 一些命令
  • 原文地址:https://www.cnblogs.com/zxw-xxcsl/p/11623305.html
Copyright © 2020-2023  润新知