• 自动化学习-Day04


    作业

    #1、注册:
        # 账号和密码存在文件里面
        # username,123456
        # username2,abc123
    #1、读写文件
    #   1、要从文件里面提取出来所有的用户名
    #   2、将注册成功的账号和密码写入文件
    
    f = open('user.txt','a+')
    f.seek(0)
    res = f.read()
    all_user_name = []
    for i in res.split('
    '):
        username = i.split(',')[0]
        all_user_name.append(username)
    
    for i in range(3):
        username = input('username:').strip()
        pwd = input('pwd:').strip()
        cpwd = input('cpwd:').strip()
        if not (len(username) >= 6 and len(username) <=20 ):
            print('用户名长度不合法')
    
        elif not (len(pwd) >= 8 and len(pwd) <=20 ):
            print('密码长度不合法')
        elif cpwd != pwd:
            print('两次输入的密码不一致')
        elif username in all_user_name:
            print('用户名已被注册')
        else:
            user_info = '%s,%s
    '%(username,pwd)
            f.write(user_info)
            print('注册成功')
            break
    else:
        print('错误次数多过')
    f.close()
    #将从文件中读出的用户名和密码转换成字典方式
    #输入与字典匹配成功,即可登陆
    all_user ={}
    res = open('user.txt').read()
    for r in res.split('
    '):
        if r.strip() != '':
            username = r.split(',')[0]
            pwd = r.split(',')[1]
            all_user[username] = pwd
    for i in range(3):
        username = input('username:')
        pwd = input('pwd:')
        if username in all_user:
            if pwd == all_user.get(username):
                print('欢迎登陆')
            else:
                print('账户/密码错误')
        else:
            print('该用户未注册')
    res = open('user.txt').read()
    username = input('username:')
    pwd = input('pwd:')
    user_info = username +','+pwd
    if user_info in res:
        print('登陆成功')
    else:
        print('登陆失败')

    字符串方法补充

    s='abcdef'
    
    users = ['username','user2','user3']
    # username,user2,user3
    
    res = ','.join(users)#1、把list变成了字符串 2、把list里面每一个元素用逗号连接起来
    print(res)
    print(s.find('z'))#返回-1
    #print(s.index('z'))#报错
    print(s.count('z'))
    print('0'.isdigit())#判断是否为正整数
    print(s.islower())
    print(s.isupper())
    print('acbe123'.isalnum()) #判断字符串里面有英文或者有数字。
    
    print('acbe'.isalpha()) #只能是字母,都是字母才返回ture
    
    print(s.isspace())#判断是否的空格
    print(s.splitlines())#以换行符分割字符串
    import string
    print(string.ascii_lowercase)
    print(string.ascii_uppercase)
    print(string.digits)
    print(string.punctuation) #特殊符号
    print(string.ascii_letters) #大小写字母
    #使用0补全数值
    l = list(range(1,100))
    new_l = []
    for i in l:
        si = str(i)
        if len(si) == 1:
            new_i = '00' + si
            new_l.append(new_i)
        elif len(si) == 2:
            new_i = '0' + si
            new_l.append(new_i)
        else:
            new_i = si
            new_l.append(new_i)
    print(new_l)
    #第二种方式
    l = list(range(1,100))
    new_l2 = []
    for i in l:
        si = str(i)
        new_l2.append(si.zfill(5))
    print(new_l2)

    文件读写

    r 只读,打开文件不存的话,会报错
    w
    只写,会清空原来文件的内容 a 追加写,不会请求,打开的文件不存在的话,也会帮你新建一个文件 r+ 读写模式 w+ 写读模式 a+ 追加读模式w+,a+打开不存在的文件不会报错,会自动生成该文件
    r+打开不存在的文件会报错
    f
    = open('users2.txt','a+',encoding='utf-8') f.seek(0) print(f.read())
    f.write(
    'a+模式') f.write('hahaha') print('',f.read())#获取到文件里面所有的内容 print(f.readlines())#获取到文件里面所有的内容,读出后是一个数组 print(f.readline())#读取一行
    f = open('users2.txt','a+')
    f1 = open('hello.txt','a+')
    f.seek(0)
    a = f.readlines()
    print(a)
    for i in a:
        f1.write(i+'
    ')
    
    u='abc,123'
    f1.writelines(u)
    f = open('user.txt',encoding='utf-8')
    while True:
        line = f.readline()
        if line !='':
            print('line:',line)
        else:
            print('文件读取完毕')
            break
    f = open('user.txt',encoding='utf-8')
    for line in f:
        print(line)
    #1、要从日志里面找到1分钟之内访问超过200次的
    #2、每分钟都运行一次
    
    # 1、读取文件内容,获取到ip地址
    # 2、把每个ip地址存起来 {}
    # 3、判断ip访问的次数是否超过200次
    # 4、加入黑名单 print
    
    #['118.24.4.30','118.24.4.30','118.24.4.30','118.1xx.x.xx','118.1xx.x.xx']
    # {
    #     '118.23.3.40':2,
    #     '118.23.3.41':5
    # }
    import time
    point = 0 #初始的位置
    while True:
        ips = {}
        f = open('access.log',encoding='utf-8')
        f.seek(point)
        for line in f: #循环取文件里面每行数据
            ip = line.split()[0] #按照空格分割,取第一个元素就ip
            if ip in ips:#判断这个ip是否存在
                # ips[ip] = ips[ip]+1
                ips[ip]+=1#如果存在的话,次数加+1
            else:
                ips[ip]=1 #如果不存在ip的次数就是1
        point = f.tell() #记录文件指针位置
        f.close()
        for ip,count in ips.items():#循环这个字典,判断次数大于200的
            if count>=200:
                print('%s 加入黑名单'%ip)
        time.sleep(60)

    修改文件内容

    #简单、粗暴直接的
    f = open(r'C:UsersDesktopfile.txt',encoding='utf-8')
    res = f.read().replace('一点','二点')
    f.close()
    f = open(r'C:UsersDesktopfile.txt',mode='w',encoding='utf-8')
    f.write(res)
    f.flush() #立即把缓冲区里面的内容,写到磁盘上
    f.close()
    f = open(r'D:file.txt','a+',encoding='utf-8')
    f.seek(0)
    res = f.read().replace('','TANG')
    f.seek(0)
    f.truncate() #清空文件里面的内容
    f.write(res)
    f.close()
    import os
    f = open(r'D:file.txt',encoding='utf-8')
    f2 = open(r'D:file.txt.bak','w',encoding='utf-8')
    for line in f:
        new_line = line.replace('TANG','')
        f2.write(new_line)
    f.close()
    f2.close()
    os.remove(r'D:file.txt')
    os.rename(r'D:file.txt.bak',r'D:file.txt')
    import os
    with open('file.txt',encoding='utf-8') as f, open('file.txt.bak','w',encoding='utf-8') as f2:
        for line in f:
            new_line = line.replace('hello','world')
            f2.write(new_line)
    os.remove('file.txt')
    os.rename('file.txt.bak','file.txt')

    处理JSON

    json.load()从文件中读取json字符串
    json.loads()将json字符串转换为字典类型
    json.dumps()将python中的字典类型转换为字符串类型
    json.dump()将json格式字符串写到文件中

    s='''
    {
            "error_code": 0,
            "stu_info": [
                    {
                            "id": 309,
                            "name": "小白",
                            "sex": "男",
                            "age": 28,
                            "addr": "河南省济源市北海大道32号",
                            "grade": "天蝎座",
                            "phone": "18512572946",
                            "gold": 100
                    },
                    {
                            "id": 310,
                            "name": "小白",
                            "sex": "男",
                            "age": 28,
                            "addr": "河南省济源市北海大道32号",
                            "grade": "天蝎座",
                            "phone": "18516572946",
                            "gold": 100
                    }
            ]
    }
    
    '''
    import json
    res = json.loads(s) #json串(字符串),转成字典
    print(res)
    print(res.keys())
    print(type(res))
    stus = {'xiaojun':'123456','xiaohei':'7891','tan':'11111'
            ,'海龙':'111'}
    res2 = json.dumps(stus,indent=8,ensure_ascii=False) #把字典对象转成字符串
    print(res2)
    print(type(res2))
    with open(
    'stus.json','w',encoding='utf-8') as f: f.write(res2) f = open('stus.json',encoding='utf-8') content = f.read() user_dic = json.loads(content) print(user_dic) f = open('stus.json',encoding='utf-8') user_dic = json.load(f) print(user_dic)
    stus = {'xiaojun':'123456','xiaohei':'7891','tan':'11111'
            ,'海龙':'111'}
    
    res2 = json.dumps(stus,indent=8,ensure_ascii=False)
    print(res2)
    with open('stus1.json','w',encoding='utf-8') as f:
        f.write(res2)
    
    f = open('stus2.json','w',encoding='utf-8')
    json.dump(stus,f,indent=4,ensure_ascii=False)

    函数

    # 函数、方法,实现特定功能的一坨代码
    # 提高代码的复用性
    import json
    def my():
        print('函数')
    #函数必须得调用才会执行
    
    #函数里面定义的变量,就是局部变量,局部变量只在函数里面可以使用
    #出了函数外面之后,就不能使用了。
    
    def get_file_content(file_name):#形参,形式参数
        #入参:传入一个文件名
        #返回值:文件内容转成字典,返回
        with open(file_name,encoding='utf-8') as f:
            res = json.load(f)
            return res
    #一个函数只做一件事
    abc = get_file_content('stus.json') #实参,实际参数
    # print(abc)
    def write_file(filename,content):
        with open(filename,'w',encoding='utf-8') as f:
            json.dump(content,f,ensure_ascii=False,indent=4)
            # f.write(json.dumps(content))
    
    d={'name':'nhy','sex':'nan'}
    d2={'aaa':'xxx','a':1}
    write_file('nhy.json',d)
    write_file('yanfan.json',d2)
    def my():
        return 1
    
    def my2():
        res = my()
        print(res+1)
    
    my2()
  • 相关阅读:
    函数的设计和使用
    python正则表达式
    Python字符串
    Python序列(十一)集合
    centos 磁盘分区、格式化及挂载
    Nginx下配置SSL证书 调转到IIS、tomcat二级站点
    Mime 类型列表
    WCF学习- 体系结构
    .NET Framework Client Profile 简介
    WCF学习- 基础概念
  • 原文地址:https://www.cnblogs.com/rongpeng/p/12012433.html
Copyright © 2020-2023  润新知