|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
模块是可用代码块的打包。 模块是一个包含所有你定义的函数和变量的文件,文件后缀名为.py 模块可以被别的程序引入,
以使用该模块中的函数等功能
- >>> secret = random.randint(1,10) # 直接用模块就会报错
- Traceback (most recent call last):
- File "<pyshell#92>", line 1, in <module>
- secret = random.randint(1,10)
- NameError: name 'random' is not defined
- >>> import random # 需要import
- >>> secret = random.randint(1,10)
- >>> secret
- 5
复制代码
OS:Operating System 操作系统模块
有了OS模块,我们不需要关心什么操作系统下使用什么模块,OS模块会帮你选择正确的模块并调用。
- >>> import os # 导入os模块
- >>> os.getcwd() # 返回当前工作目录
- 'E:\\小甲鱼python练习题\\002'
- >>> os.chdir('E:\\') # 改变目录
- >>> os.getcwd()
- 'E:\\'
- >>> os.listdir('E:\\') # 显示目录中的文件名
- ['$RECYCLE.BIN', 'BaiduNetdiskDownload', 'DCIM', 'iTunes', 'Linux视频', 'My_software', 'NS', 'pycharm_test', 'python视频', 'QMDownload', 'System Volume Information', 'test.txt', 'virtualbox_centos', 'VMware', '小甲鱼python练习题']
- >>> os.mkdir("E:\\A") # 创建目录
- >>> os.mkdir("E:\\A\\B")
- >>> os.mkdir("E:\\C\\B") # 因不存在C目录,所以会报错
- Traceback (most recent call last):
- File "<pyshell#103>", line 1, in <module>
- os.mkdir("E:\\C\\B")
- WindowsError: [Error 3] 系统找不到指定的路径。: 'E:\\C\\B'
- >>> os.rmdir('E:\\A\\B') # 因B目录非空,所以删除会报错
- Traceback (most recent call last):
- File "<pyshell#104>", line 1, in <module>
- os.rmdir('E:\\A\\B')
- WindowsError: [Error 145] 目录不是空的。: 'E:\\A\\B'
- >>> os.remove('E:\\A\\B\\test.txt') # 删除文件
- >>> os.rmdir('E:\\A\\B') # 删除空目录
- >>> os.system('cmd') # 打开cmd
- >>> os.system('calc') #打开计算器
- 0
- >>> os.curdir # 指代当前目录, .表示当前目录 .. 表示当前目录的父目录
- '.'
- >>> os.listdir(os.curdir) # 显示当前目录下的所有文件
- ['$RECYCLE.BIN', 'A', 'BaiduNetdiskDownload', 'DCIM', 'iTunes', 'Linux视频', 'My_software', 'NS', 'pycharm_test', 'python视频', 'QMDownload', 'System Volume Information', 'test.txt', 'virtualbox_centos', 'VMware', '小甲鱼python练习题']
复制代码
以下是os.path模块
- >>> os.path.basename('E:\\A\\B\\C\\sexy.avi') # 返回文件名
- 'sexy.avi'
- >>> os.path.dirname('E:\\A\\B\\C\\sexy.avi') # 返回目录路径
- 'E:\\A\\B\\C'
- >>> os.path.join('A','B','C') # 把 A B C组合成一个路径名
- 'A\\B\\C'
- >>> os.path.join('C:','A','B','C')
- 'C:A\\B\\C'
- >>> os.path.join('C:\\','A','B','C') # 完整的例子
- 'C:\\A\\B\\C'
复制代码
- >>> os.path.split('E:\\A\\SEXY.AVI') # 将文件名与路径分割
- ('E:\\A', 'SEXY.AVI')
- >>> os.path.split('E:\\A\\B\\C') #默认会将最后一个看成是文件名
- ('E:\\A\\B', 'C')
- >>> os.path.splitext('E:\\A\\SEXY.AVI') # 分割文件名和扩展名
- ('E:\\A\\SEXY', '.AVI')
复制代码
- >>> os.path.getatime('E:\\test.txt') # 显示文件最近访问时间
- 1501560683.6592071
- >>> import time # 导入time模块
- >>> time.gmtime(os.path.getatime('E:\\test.txt')) # gtime是标准时间
- time.struct_time(tm_year=2017, tm_mon=8, tm_mday=1, tm_hour=4, tm_min=11, tm_sec=23, tm_wday=1, tm_yday=213, tm_isdst=0)
- >>> time.localtime(os.path.getatime('E:\\test.txt')) #localtime是东八区时间
- time.struct_time(tm_year=2017, tm_mon=8, tm_mday=1, tm_hour=12, tm_min=11, tm_sec=23, tm_wday=1, tm_yday=213, tm_isdst=0)
- >>> os.path.ismount('E:\\') # 判断E盘是否为挂载点
- True
- >>> os.path.ismount('E:\\A') # A不是挂载点
- False
- >>>
复制代码
|
评分
-
查看全部评分
|