2021/1/12 小练习(python)

输入一个用户名和密码,密码进行加密处理,并将用户名和密码存储在一个字典中,字典的键值为用户名,值为密码,并且以json的形式写入文件

import hashlib
import json
username = input('请输入用户名:')
password = input('请输入密码:')
dic = dict()
ret = hashlib.md5()
ret.update(password.encode('utf-8'))
password = ret.hexdigest()
dic[username] = password
print(dic)

with open('1.json', 'a', encoding='utf-8') as f1:
    f1.write(json.dumps(dic))
    f1.write('\n')

with open('1.json', 'r', encoding='utf-8') as f2:
    print(f2.read())

利用递归寻找文件夹中所有的文件,并将这些文件的绝对路径添加到一个列表中:

import os

def findpath(path,li = []):
    path_abs = path
    path_list = os.listdir(path)
    for i in path_list:
        if os.path.isfile(os.path.join(path_abs, i)):
            li.append(os.path.join(path_abs, i))
        else:
            findpath(os.path.join(path_abs, i))
    return li

print(findpath(r'C:\Users\ping\PycharmProjects\untitled'))

写函数:用户输入某年某月某日,判断这是这一年的第几天

import time
def find_day(day):
    ret = time.strptime(day, "%Y-%m-%d")
    return ret.tm_yday

print(find_day('2021-9-12'))

生成随机4位的验证码

#方法一
import random
li = ([str(i) for i in range(0, 11)]+[str(chr(i)) for i in range(ord('a'), ord('z')+1)] + [str(chr(i)) for i in range(ord('A'), ord('Z')+1)])
str_code = ""
for i in random.sample(li, 4):
    str_code += str(i)
print(str_code)

#方法2:
import random
def code():
    str_code = ""
    for i in range(4):
        num = str(random.randint(0, 9))
        low_char = chr(random.randint(97, 122))
        upper_char = chr(random.randint(65, 90))
        str_s = random.choice([num, low_char, upper_char])
        str_code += str_s
    return str_code

print(code())

 

posted @ 2021-01-12 13:08  ping_sen  阅读(53)  评论(0)    收藏  举报