pyrhon学习——常用模块联系

# 1.回顾文件递归遍历. 默写一遍.
# 入口在: 当文件是个文件夹的时候
# 出口在: 文件是一个文件
import os
def func(path,n=0):
    path_list = os.listdir(path) #打开文件夹,查看当前目录的文件
    for name in path_list: #遍历path路径下所有文件名
        abs_path = os.path.join(path,name) #将所有文件拼为绝对路径
        if os.path.isdir(abs_path): # 判断文件是否为文件夹
            print('	'*n,name,':') # 如果是文件夹打印文件夹名字
            func(abs_path,n+1) #将当前判断后的绝对路径文件返回path重新执行func,文件层数+1,多一层对一个'	'
        else:
            print('	'*n,name) # 不是文件夹打印文件名
ret = func('E:python')
# 2.计算时间差(用户输入起始时间和结束时间. 计算时间差(小时),
# 例如, 用户输入2018-10-08 12:00:00 2018-10-08 14:30:00 输出2小时
import time
stime = time.strptime('2019-8-15 5:00:00','%Y-%m-%d %H:%M:%S')
etime = time.strptime('2019-8-18 12:32:43','%Y-%m-%d %H:%M:%S')
sub_time = time.mktime(etime) - time.mktime(stime)
gm_time = time.gmtime(sub_time)
print('过去了%d年%d月%d日%d小时%d分%d秒' %(gm_time.tm_year-1970,gm_time.tm_mon-1,
                                      gm_time.tm_mday-1,gm_time.tm_hour,
                                      gm_time.tm_min,gm_time.tm_sec))
# 3.写一个函数,接收一个参数,如果是文件,就执行这个文件,
# 如果是文件夹,就执行这个文件夹下的所有的py文件。
#思路:
#先判断这个path是文件还是文件夹
#如果是文件:.py结尾的,执行文件:os.system('python path')
#如果是文件夹:查看文件夹下的所有内容,如果是文件.py结尾则执行
import os
def exec_py(path):
    if os.path.isfile(path) and path.endwith('.py'): #判断路径是否为文件且以py结尾
        os.system('python %s'%path) # py结尾就执行
    elif os.path.isdir(path): # 判断是否是文件夹
        path_list = os.listdir(path)  # 查看文件夹下的所有文件
        for name in path_list:    # 遍历所有文件的文件名
            abs_path = os.path.join(path,name)        # 将文件名拼为绝对路径
            if os.path.isfile(abs_path) and abs_path.endswith('.py'): # 判断绝对路径是否为文件且py结尾
                os.system('python %s' % abs_path) # 是则执行文件
            elif os.path.isdir(abs_path): # 判断是否为文件夹
                exec_py(abs_path) #是则调用函数
exec_py(r'E:pythonToolsday 15')
# 4.写一个copy函数,接受两个参数,第一个参数是源文件的位置,第二个参数是目标位置,
# 将源文件copy到目标位置。
import os
def copy(path1,path2):
    new_filename = os.path.basename(path1)
    path2 = os.path.join(path2,new_filename)
    with open('path1','rb') as f1,
        open('path2','wb') as f2:
            ret = f1.read()
            f2.write(ret)
copy(r'E:pythonToolsday 18json_file',r'E:pythonToolsday17')
# 5.获取某个文件所在目录的上一级目录。
import os
ret = os.path.dirname(r'E:pythonTools老男孩day 18json_file')
re_ret = os.path.dirname(ret)
print(re_ret)
# 6.使用os模块创建如下目录结构
# glance
# ├── __init__.py
# ├── api
# │ ├── __init__.py
# │ ├── policy.py
# │ └── versions.py
# ├── cmd
# │ ├── __init__.py
# │ └── manage.py
# └── db
# ├── __init__.py
# └── models.py
import os
os.makedirs('glance')
os.makedirs('glance/api')
os.makedirs('glance/cmd')
os.makedirs('glance/db')
open(r'E:pythonToolsday 18glance\__init__.py','w').close()
open(r'E:pythonToolsday 18glanceapi\__init__.py','w').close()
open(r'E:pythonToolsday 18glanceapipolicy.py','w').close()
open(r'E:pythonToolsday 18glanceapiversions.py','w').close()
open(r'E:pythonToolsday 18glancecmd\__init__.py','w').close()
open(r'E:pythonToolsday 18glancecmdmanage.py','w').close()
open(r'E:pythonToolsday 18glancedb\__init__.py','w').close()
open(r'E:pythonTools老day 18glancedbmodels.py','w').close()
# 7.写一个用户注册登陆的程序,
# 每一个用户的注册都要把用户名和密码用字典的格式写入文件userinfo。
# 在登陆的时候,再从文件中读取信息进行验证。
import pickle
def regist():
    usr = input('用户名:')
    pwd = input('密码:')
    inf = {'usr':usr,'pwd':pwd}
    with open('pickle_file','ab') as f:
        pickle.dump(inf,f)
    print('注册完成')
def login():
    usr = input('用户名:')
    pwd = input('密码:')
    with open('pickle_file','rb') as f:
        while 1:
            try:
                inf = pickle.load(f)
                if inf['usr'] == usr and inf['pwd'] == pwd:
                    print('登录成功')
                    break
                else:
                    print('账号密码错误')
            except EOFError:
                print('登陆失败')
                break
login()
# 8.使用random模块,编写一个发红包的函数
import random
def send_money(money,num):
    money = money*100
    ret = random.sample(range(1,money),num - 1)
    ret.sort()
    ret.insert(0,0)
    ret.append(money)
    print(ret)
    for i in range(len(ret)-1):
        yield(ret[i+1]-ret[i])/100
ret_g = send_money(100,10)
for i in ret_g:
    print(i)
原文地址:https://www.cnblogs.com/bilx/p/11358600.html