• 【四】文件与异常2


    文件

    在我们读写一个文件之前需要打开文件

    data=open(filename,mode)
    1. data是open()返回的文件对象
    2. filename是该文件的字符串名
    3. mode是文件类型和操作的字符串

    mode第一个字母的文件类型:

    • r:只读。这是默认模式
    • r+:可读可写,不会创建不存在的文件,如果直接写文件,则从顶部开始写,覆盖之前此位置的内容
    • w:只写,如果文件不存在则新建,如果已存在则覆盖内容
    • w+:读写,如果文件不存在则新建,如果已存在则覆盖
    • x:在文件不存在的情况下新建并写文件

    mode第二个字母的文件类型:

    • t:文本类型
    • b:二进制文件

    使用write()写文本文件

    使用write写入:

    In [66]: poems='白日依山尽,黄河入海流,日穷千里目,更上一层楼'
    #打印poems的字节大小
    In [67]: len(poems)
    Out[67]: 23
    #打开test.txt
    In [68]: fout=open('test.txt','wt')
    #将poems的内容写入
    In [70]: fout.write(poems)
    Out[70]: 23 #函数 write() 返回写入文件的字节数
    #关闭连接
    In [71]: fout.close()
    In [72]: cat test.txt
    白日依山尽,黄河入海流,日穷千里目,更上一层楼

    使用print写入:

    In [1]: poem="鹅鹅鹅,曲项向天歌,白毛浮绿水,红掌拨清波"
    In [2]: fout=open('test.txt','wt')
    In [3]: print(poem,file=fout)
    In [4]: fout.close()
    In [5]: cat test.txt
    鹅鹅鹅,曲项向天歌,白毛浮绿水,红掌拨清波
    • sep 分隔符:默认是一个空格 ‘ ‘
    • end 结束字符:默认是一个换行符 ‘ ’
    In [4]: fout=open('test.txt','w')
    In [5]: poem="加油,好好学习,天天向上"
    In [6]: print(poem,file=fout,sep='',end='')
    In [7]: cat test.txt
    In [8]: fout.close()
    In [9]: cat test.txt
    加油,好好学习,天天向上

    如果字符串非常大,可以将数据分块,直到所有字符被写入:

    In [14]: poem
    Out[14]: '鹅鹅鹅,曲项向天歌,白毛湖绿水,红掌拨清波'
    In [15]: fout=open('libai.txt','w')
    In [16]: off=0
    In [17]: chunk=10
    In [18]: while True:
        ...:     if off>size:
        ...:         break
        ...:     fout.write(poem[off:off+chunk])
        ...:     print(poem[off:off+chunk])
        ...:     off+=chunk
        ...:     
    鹅鹅鹅,曲项向天歌,
    白毛湖绿水,红掌拨清
    波
    In [19]: fout.close()

    如果 libai.txt 文件已经存在,使用模式 x 可以避免重写文件:

    In [21]: fout=open('libai.txt','xt')
    ---------------------------------------------------------------------------
    FileExistsError                           Traceback (most recent call last)
    <ipython-input-21-2bb5519d7012> in <module>()
    ----> 1 fout=open('libai.txt','xt')
    
    FileExistsError: [Errno 17] File exists: 'libai.txt'

    使用 read()、readline() 或者 readlines() 读取文本文件

     使用不带参数的 read() 函数一次读入文件的所有内容。

    In [22]: fin=open('libai.txt','rt')
    In [23]: poem1=fin.read()
    In [24]: poem1
    Out[24]: '鹅鹅鹅,曲项向天歌,白毛湖绿水,红掌拨清波'
    In [25]: fin.close()
    In [26]: len(poem1)
    Out[26]: 21

     函数 readlines() 调用时每次读取一行,并返回单行字符串的列表

    In [28]: poem='''鹅鹅鹅,
        ...: 曲项向天歌,
        ...: 白毛湖绿水,
        ...: 红掌拨清波。
        ...: '''
    In [29]: fin=open('libai.txt','wt') #写入文件
    In [30]: fin.write(poem)
    Out[30]: 26
    In [31]: fin.close()
    In [32]: cat libai.txt
    鹅鹅鹅,
    曲项向天歌,
    白毛湖绿水,
    红掌拨清波。
    In [33]: fin=open('libai.txt','rt') #读取文件
    In [34]: lines=fin.readlines()
    In [35]: fin.close()
    In [36]: lines
    Out[36]: ['鹅鹅鹅,
    ', '曲项向天歌,
    ', '白毛湖绿水,
    ', '红掌拨清波。
    ']
    In [37]: print(len(lines))
    4
    In [41]: for line in lines:
        ...:     print(line,end='')
        ...:     
    鹅鹅鹅,
    曲项向天歌,
    白毛湖绿水,
    红掌拨清波。

     习题:

    验证一个文本里面的密码,如果正确返回,不正确重试3次
    # coding=utf-8
    """
    验证一个文本里面的密码,如果正确返回,不正确重试3次
    """
    count=0
    #获取password.txt中的文本内容
    def get_password():
        try:
            with open('passwd.txt') as f:
                passwd=int(f.readline().strip())
            return passwd
        except IOError as e:
            raise e
    while count<3:#退出的循环条件
        user_passwd=input('请输入密码:')
        passwd=get_password()
        if user_passwd!=passwd: #通常做法,比较不相等的情况
            print("密码错误,请重试!(最多重试3次)")
            count +=1
            continue
        print("密码正确")
        break
    else:
        print("重试超过3次,退出")
    答案:

     习题二:使用写入文件和读取文件的方式,写一个注册登陆的功能

    #coding=utf-8
    """
    需求:做一个登陆注册的功能
    """
    #1.打开文件操作
    #2.更新文件操作
    #3.注册函数
    #4.登陆函数
    import pickle #引入pickle包
    def open_file():
        try:
            with open("data.txt","rb") as f:
                return pickle.load(f)
        except IOError as e:
            return False
        except Exception as e:
            raise e
    def updata_file(user_data):
        try:
            with open("data.txt","wb") as f:
                pickle.dump(user_data,f)
                return True
        except IOError as e:
            return False
        except Exception as e:
            raise e
    #需对用户名做判断,如果存在,提示“用户名已存在”
    def zc():
        username=raw_input("请输入用户名:")
        user_data=open_file()
        print(type(user_data))
        if username in user_data.keys():
            print("用户名已存在")
            return False
        userpawd=raw_input("请输入密码:")
        userdata={username:userpawd}    #使用字典的方式将username和password存进去
        db_status=updata_file(userdata)
        if not db_status:
            print("注册失败")
        print("注册成功")
    def dl():
        count=0
        while count<3:
            username=raw_input("请输入用户名:")
            userpassword=raw_input("请输入密码:")
            user_data=open_file()
            passwd=user_data.get(username)
            if passwd is None:
                print("用户不存在")
                break
            if passwd!=userpassword:
                print("密码错误,请重试(最多3次)")
                continue
            print("密码正确,登陆成功")
            break
        else:
            print("重试了3次,退出")
    if __name__=="__main__":
        while True:
            user_xz=raw_input("1 注册,2登陆,3退出")
            if user_xz=="1":
                zc()
            elif user_xz=="2":
                dl()
            else:
                break

    执行结果:

  • 相关阅读:
    牛客多校第一场 A Equivalent Prefixes 单调栈(笛卡尔树)
    HDU多校第三场 Hdu6606 Distribution of books 线段树优化DP
    (待写)
    Hdu6586 String 字符串字典序贪心
    2019HDU多校第一场1001 BLANK (DP)(HDU6578)
    iOS触摸事件
    iOS获取相册/相机图片-------自定义获取图片小控件
    自定义表情输入框
    iOS版本、iPhone版本、Xcode版本比对
    Swift备忘录
  • 原文地址:https://www.cnblogs.com/8013-cmf/p/7000864.html
Copyright © 2020-2023  润新知