1. 小程序:根据用户输入选择可以完成以下功能:

    创意文件,如果路径不存在,创建文件夹后再创建文件


    能够查看当前路径


    在当前目录及其所有子目录下查找文件名包含指定字符串的文件

import os
choice={
"1":"创建文件",
"2":"查看当前路径",
"3":"查找文件名",
"4":"退出程序"
} def mkdir():
file_path = input("please input your file_path:").strip()
try:
os.chdir(file_path)
print("%s存在,不需要重新创建" % file_path)
except:
print("%s不存在,开始创建文件" % file_path)
os.makedirs(file_path)
print("%s创建完成" % file_path) def check():
file_name = input("please input your file_name:").strip()
try:
print("%s绝对路径为:%s"%(file_name,os.path.abspath(file_name)))
except:
print("%s不存在,开始创建文件" % file_name) def search():
file_dir = input("please input your file_dir:").strip()
print("当前目录为:%s,子目录和所有文件为:%s" % (os.getcwd(), os.listdir(os.getcwd()))) while True:
for key in choice:
print(key,choice[key])
num=int(input("please input your choice:").strip()) if num==1:
mkdir() elif num==2:
check() elif num == 3:
search() elif num==4:
break

  

2. 将三次登陆锁定的作业改为:python login.py -u alex -p 123456 输入的形式(-u,-p是固定的,分别代表用户名和密码)

#将三次登陆锁定的作业改为:
# python login.py -u alex -p 123456 输入的形式
# (-u,-p是固定的,分别代表用户名和密码)
import sys
if(sys.argv[sys.argv.index("-u")+1] == "egon" and sys.argv[sys.argv.index("-p")+1] == "somebody" ):
print("Congratulations")
else:
print("Error")
#!/bin/python3
# -*- coding:utf-8 -*-
''' python login auth example '''
#imports
import getpass,os,sys
#functions
def lock_user(username):
''' username -> modify userlist file '''
temp_str = ""
with open("userlist.swp",'w') as file_write , open("userlist",'r') as file_read:
for line in file_read:
temp_list = eval(line)
if temp_list[0] == username:
temp_list[2] += 1
temp_str += str(temp_list)+"\n"
continue
temp_str += line
file_write.write(temp_str)
os.rename("userlist.swp", "userlist")
def unlock_user(username):
''' username -> modify userlist file '''
temp_str = ""
with open("userlist.swp",'w') as file_write , open("userlist",'r') as file_read:
for line in file_read:
temp_list = eval(line)
if temp_list[0] == username:
temp_list[2] = 0
temp_str += str(temp_list)+"\n"
continue
temp_str += line
file_write.write(temp_str)
os.rename("userlist.swp", "userlist")
def user_input():
''' input username&&password -> return username&&password '''
if not "-u" in sys.argv and not "-p" in sys.argv:
print("help:\n-u [username] -p [password]")
exit()
username = sys.argv[sys.argv.index("-u")+1]
password = sys.argv[sys.argv.index("-p")+1]
# username = input("username:")
# password = getpass.getpass("password:")
return username,password
def check_user(username,password = '',type = 'check'):
'''
username,password,check -> return t||f #username password lock check
username,password,lock -> return t||f #username locked or not
'''
flag = False
with open("userlist",'r') as file_read:
for line in file_read:
temp_list = eval(line)
if type == 'check':
if username == temp_list[0] and password == temp_list[1] \
and temp_list[2] < 2:
return True #user not locked and correct user and pass
if type == 'lock':
if username == temp_list[0] and temp_list[2] >= 2:
return True #user has been locked else:
return False
#login decorator
def auth(func):
def wrapper(*args,**kwargs):
username,password = user_input() #get input
# if not username and not password:
# print("incorrect username or password!")
# exit()
if check_user(username, password,type='check'): #juge username and password correct or not
print("login success!")
unlock_user(username)
func(username) #shell function
else:
if check_user(username, password, type='lock'): #juge user locked or not
print("This account has been locked!")
else:
lock_user(username) #lock count += 1
print("incorrect username or password!")
return wrapper
#shell function
@auth
def login_index(username = ""):
''' shell program '''
while True:
command = input("%s>" %username) #ask input command
if command == 'ls':
print(
'''
bin dev home lib64 media opt root sbin sys usr
boot etc lib lost+found mnt proc run srv tmp var
''')
if command == 'exit': #exit shell
print("byebye!")
exit() def main():
''' main program '''
login_index() #program entry
if __name__ == '__main__':
main()

  

3. 层级结构:


    dir1


    ---hello.py


    dir2


    ---main.py


    其中,hello.py:


    def add(x,y):


        
return x+y

 main.py如何能调用到hello.py中的add函数?

参考博客结尾的内容,单独导入包。http://www.cnblogs.com/xuyaping/p/6797032.html

注:此题中导入的模块只是一个简单的模块,和博客中导入模块不同的是没有__init__文件,更简单些。

#main.py
import sys,os
sys.path.append("E:\python学习\day33常用模块\作业\dir1")
print(sys.path)
--->['E:\\python学习\\day33常用模块\\作业\\dir2', 'E:\\python学习', 'C:\\Users\\Administrator.PC-201509301704\\AppData\\Local\\Programs\\Python\\Python36\\python36.zip', 'C:\\Users\\Administrator.PC-201509301704\\AppData\\Local\\Programs\\Python\\Python36\\DLLs', 'C:\\Users\\Administrator.PC-201509301704\\AppData\\Local\\Programs\\Python\\Python36\\lib', 'C:\\Users\\Administrator.PC-201509301704\\AppData\\Local\\Programs\\Python\\Python36', 'C:\\Users\\Administrator.PC-201509301704\\AppData\\Local\\Programs\\Python\\Python36\\lib\\site-packages', 'E:\\python学习\\day33常用模块\\作业\\dir1'] import hello
print(hello.add(1,2))
--->3

4. 显示当前时间三天后是星期几?

import time
c=time.localtime()
print(c) #当前时间
--->time.struct_time(tm_year=2017, tm_mon=4, tm_mday=26, tm_hour=23, tm_min=40, tm_sec=54, tm_wday=2, tm_yday=116, tm_isdst=0) t=time.time()-3600*24*3
print(time.localtime(t))
--->time.struct_time(tm_year=2017, tm_mon=4, tm_mday=23, tm_hour=23, tm_min=44, tm_sec=30, tm_wday=6, tm_yday=113, tm_isdst=0) print(time.localtime(t).tm_wday)
--->6

  

python(31)- 模块练习的更多相关文章

  1. python基础-模块

    一.模块介绍                                                                                              ...

  2. Day05 - Python 常用模块

    1. 模块简介 模块就是一个保存了 Python 代码的文件.模块能定义函数,类和变量.模块里也能包含可执行的代码. 模块也是 Python 对象,具有随机的名字属性用来绑定或引用. 下例是个简单的模 ...

  3. python 各模块

    01 关于本书 02 代码约定 03 关于例子 04 如何联系我们 1 核心模块 11 介绍 111 内建函数和异常 112 操作系统接口模块 113 类型支持模块 114 正则表达式 115 语言支 ...

  4. python random模块 - 小驹的专栏 - 博客频道 - CSDN.NET

    python random模块 - 小驹的专栏 - 博客频道 - CSDN.NET python random模块 分类: python 2011-11-15 15:31 6037人阅读 评论(2) ...

  5. Day5 模块及Python常用模块

    模块概述 定义:模块,用一砣代码实现了某类功能的代码集合. 为了编写可维护的代码,我们把很多函数分组,分别放到不同的文件里,提供了代码的重用性.在Python中,一个.py文件就称之为一个模块(Mod ...

  6. SUSE Linux Enterprise 11 离线安装 DLIB python机器学习模块

    python机器学习模块安装 环境:SUSE Linux Enterprise 11 sp4  离线安装 说明:在安装dlib时依赖的基础 环境较多,先升级gcc,以适应c++ 11的使用:需要用到c ...

  7. Python(五)模块

    本章内容: 模块介绍 time & datetime random os sys json & picle hashlib XML requests ConfigParser logg ...

  8. Thread类的其他方法,同步锁,死锁与递归锁,信号量,事件,条件,定时器,队列,Python标准模块--concurrent.futures

    参考博客: https://www.cnblogs.com/xiao987334176/p/9046028.html 线程简述 什么是线程?线程是cpu调度的最小单位进程是资源分配的最小单位 进程和线 ...

  9. Python之模块和包

    一.模块 1.什么是模块? 常见的场景:一个模块就是一个包含了python定义和声明的文件,文件名就是模块名字加上.py的后缀. 但其实import加载的模块分为四个通用类别: 1 使用python编 ...

  10. python常用模块之时间模块

    python常用模块之时间模块 python全栈开发时间模块 上次的博客link:http://futuretechx.com/python-collections/ 接着上次的继续学习: 时间模块 ...

随机推荐

  1. [错误解决]Ubuntu中使用dpkg安装deb文件提示依赖关系问题,仍未被配置

    使用dpkg进行软件安装时,提示:dpkg:处理软件包XXX时出错:依赖关系问题,仍未被配置 使用如下命令,sudo apt-get install -f 等分析完之后,重新使用dpkg –i XXX ...

  2. PDO PDO_MYSQL MYSQLI MYSQL 的区别

    MYSQL,MYSQLI 这两个扩展本身就是访问MYSQL数据库的驱动 PDO则是一个抽象层接口 向程序员提供可调用的API是由,MYSQL驱动.MYSQLI驱动,以及PDO来提供. PDO_MYSQ ...

  3. Jboss性能调优

    1,Jboss5调优指南 https://www.redhat.com/f/pdf/JB_JEAP5_PerformanceTuning_wp_web.pdf 1,Jboss7.1 性能调优指南 a: ...

  4. netcore命令行部署|跨域问题

    1.在hosting中修改发布端口号,如遇见不识别IP则改成*再用命令行运行 { "server.url": "http://*:8089"} 3.给接口开外网 ...

  5. 设计模式(八)组合模式 Composite

    组合模式: 允许你将对象组合成树形结构来表现“整体/部分”层次结构.组合能让客户以一致的方式处理个别对象以及对象组合. 组合模式适用于创建复杂的对象,这个对象包含某些个别的对象以及这些对象的组合. 从 ...

  6. 【BJOI2014/bzoj4530】大融合

    题意 有 $n$ 个点,初始没有连边,要求支持两个动态操作: 1. 加一条边(保证之前两点不连通) 2. 查询过一条边的简单路径数量(就是两边连通块的大小的乘积) $n,Q\le 100000$ 题解 ...

  7. 解决 Jackson反序列化 Unexpected token ... , expected VALUE_STRING: need JSON String that contains type id (for subtype of ...)

    首先检查是否是 objectMapper.enableDefaultTyping(); 的受害者.优先考虑删除该配置. 使用Jackson把数组的json字符串反序列化为List时候报了个JsonMa ...

  8. springboot获取getBean方法以及ApplicationContext空指针问题解决

    创建获取ApplicationContext工具类: package com.performancetest.common.utils; import org.springframework.bean ...

  9. SPOJ QTREE3 - Query on a tree again!

    You are given a tree (an acyclic undirected connected graph) with N nodes. The tree nodes are number ...

  10. 洛谷P1101 单词方阵

    题目描述 给一nXn的字母方阵,内可能蕴含多个“yizhong”单词.单词在方阵中是沿着同一方向连续摆放的.摆放可沿着8个方向的任一方向,同一单词摆放时不再改变方向,单词与单词之间[color=red ...