• python-code-08


    今日作业:
    一、实现用户注册功能
    思路:
    用户输入用户名、密码
    将用户输入的内容按照固定的格式,比如:egon:123,存入文件
    可以往一个文件中重复注册新的用户名和密码
    while True:
        name_inp = input('name>>: ').strip() #要验证用户名得事先创建这个文件
        pwd_inp = input('password>>: ')
        chk_pwd_inp = input('password>>: ')
        if pwd_inp == chk_pwd_inp:
            with open('db_file',mode='at',encoding='utf-8') as f:
                f.write('%s:%s
    ' %(name_inp,pwd_inp))
        else:
            print('两次密码不一致')
    View Code

    二、实现用户验证功能更:
    思路:
    用户输入账号密码,从文件中读出账号密码,与用户输入的进行比对
    name_inp = input('username>>: ').strip()
    pwd_inp = input('password>>: ')
    with open('db_file',mode='rt',encoding='utf-8') as f:
        for line in f:
            line = line.strip('
    ')
            line = line.split(':')
            name = line[0]
            pwd = line[1]
            if name_inp == name and pwd_inp == pwd:
                print('验证成功')
                break
        else:
            print('用户名或密码错误')
    View Code

    三、编写程序,实现文件拷贝功能
    思路:
    用户输入源文件路径和目标文件路径,执行文件拷贝

    import sys
    if len(sys.argv) != 3:
        print('usage: cp source_file target_file')
        sys.exit()
    source_file,target_file=sys.argv[1],sys.argv[2]
    with open(source_file,'rb') as read_f,open(target_file,'wb') as write_f:
        for line in read_f:
            write_f.write(line)
    View Code


    明早默写:
    循环读取文件
    f=open('db_file','rt',encoding='utf-8')
    for line in f:
        print(line)
    f.close()
    with open('db_file',mode='rt',encoding='utf-8') as f:
        for line in f:
            print(line,end='')
    View Code

    只读的方式读取文件,并说明注意事项
    with open('db_file',mode='rt',encoding='utf-8') as f:
        print(f.read())
    1、只能读,不能写
    2、在文件不存在时,会报错,在文件存在的时候会将文件指针移动到文件的开头,读完就在末尾了
    View Code

    只写的方式写文件,并说明注意事项
    with open('w',mode='wt',encoding='utf-8') as f:
        f.write('w')
    1、只能写,不能读
    2、在文件不存在时会创建空文件,在文件存在的时候会将文件内容清空
    View Code

    只追加写的方式写文件,并说明注意事项
    with open('w',mode='at',encoding='utf-8') as f:
        f.write('
    r')
    1、只能写,不能读
    2、在文件不存在时会创建空文件,在文件存在的时候会将指针移动到文件末尾
    View Code

    简述t与b模式的区别
    t模式:只有文本文件才能用t模式,也只有文本文件才有字符编码的概念
    b模式:一定不能指定字符编码,只有t模式才与字符编码有关
    b是二进制模式,是一种通用的文件读取模式,因为所有的文件在硬盘中都是以二进制形式存放的
    View Code
  • 相关阅读:
    游标、锁
    树形背包浅谈
    金字塔
    Codeforces Round #652 (Div. 2) 题解
    NOI1999 棋盘分割
    NEERC2002 Folding
    HDU4283 You Are the One
    Codeforces Round #646 (Div. 2) 题解
    洛谷 P1679 神奇的四次方数
    UVA12563 劲歌金曲
  • 原文地址:https://www.cnblogs.com/xujinjin18/p/9157986.html
Copyright © 2020-2023  润新知