Python学习第二阶段Day2,模块time/datetime、random、os、sys、shutil
1.Time、 Datetime(常用)
UTC时间:为世界标准时间,时区为0的时间
北京时间,UTC+8东八区
import time print(time.time()) # timestamp,float
print(time.localtime()) # tuple: UTC+8 tm_year=2017, tm_mon=7, tm_mday=26, tm_hour=5, tm_min=36,
# tm_sec=50, tm_wday=2, tm_yday=207, tm_isdst=0
print(time.gmtime()) # tuple: 标准时间UTC print(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())) # 2017-07-26 05:42:20 print(time.ctime()) # Wed Jul 26 17:56:13 2017
print(time.asctime(time.localtime())) # tuple convert to Wed Jul 26 17:56:13 2017
print(datetime.datetime.now()) #返回 2016-08-19 12:47:03.941925
print(datetime.date.fromtimestamp(time.time())) # 时间戳直接转成日期格式 2016-08-19
print(datetime.datetime.now())
print(datetime.datetime.now() + datetime.timedelta(3)) #当前时间+3天
print(datetime.datetime.now() + datetime.timedelta(-3)) #当前时间-3天
print(datetime.datetime.now() + datetime.timedelta(hours=3)) #当前时间+3小时
print(datetime.datetime.now() + datetime.timedelta(minutes=30)) #当前时间+30分 c_time = datetime.datetime.now()
print(c_time.replace(minute=3,hour=2)) #时间替换
2.Random
import random
print (random.random()) # [0,1) 范围内的浮点数 0.3459334502763365
print (random.randint(1,7)) # [1,7] 范围内的int
print (random.randrange(1,10)) #
#random.randrange的函数原型为:random.randrange([start], stop[, step]),
# 从指定范围内,按指定基数递增的集合中 获取一个随机数。如:random.randrange(10, 100, 2),
# 结果相当于从[10, 12, 14, 16, ... 96, 98]序列中获取一个随机数。
# random.randrange(10, 100, 2)在结果上与 random.choice(range(10, 100, 2) 等效。 print(random.choice('liukuni')) #i
#random.choice从序列中获取一个随机元素。
# 其函数原型为:random.choice(sequence)。参数sequence表示一个有序类型。
# 这里要说明一下:sequence在python不是一种特定的类型,而是泛指一系列的类型。
# list, tuple, 字符串都属于sequence。有关sequence可以查看python手册数据模型这一章。
# 下面是使用choice的一些例子:
print(random.choice("学习Python"))#学
print(random.choice(["JGood","is","a","handsome","boy"])) #列表元素随机一个
print(random.choice(("Tuple","List","Dict"))) #tuple元素的随机一个
print(random.sample([1,2,3,4,5],3)) #[1, 2, 5]
#random.sample的函数原型为:random.sample(sequence, k),从指定序列中随机获取指定长度的片断。sample函数不会修改原有序列。
# --------------------------- 应用----------------------------------
#随机浮点数:
print( random.random()) #0.2746445568079129
print(random.uniform(1, 10)) #9.887001463194844 #随机字符:
print(random.choice('abcdefg&#%^*f')) #f #多个字符中选取特定数量的字符:
print(random.sample('abcdefghij',3)) #['f', 'h', 'd'] #随机选取字符串:
print( random.choice ( ['apple', 'pear', 'peach', 'orange', 'lemon'] )) #apple
#洗牌#
items = [1,2,3,4,5,6,7]
print(items) #[1, 2, 3, 4, 5, 6, 7]
random.shuffle(items)
print(items) #[1, 4, 7, 2, 5, 3, 6]
1.os 和 sys
import os
a = os.system("dir") 只是把结果输出到屏幕就完了,a得到dir命令执行的返回值,0或非0
str = os.popen("dir").read() # os.popen("dir")是内存地址,str是打印输出的字符串
import sys
print(sys.path) # 这个是库的路径,找库就在这些路径中找。 ../base/libray自己的库 和../base/libray/site-package第三方库
sys.argv 脚本的相对路径
sys.argv[1] 表示脚本的第一个参数
3.os模块
import os os.getcwd() # pwd
os.chdir("d:\\") # cd
os.curdir # .
os.pardir # ..
os.makedirs("d:\\fff\\fff") # 递归创建目录
os.removedirs("d:\\fff\\fff") # 递归删除清理空文件夹
os.mkdir("d:\\aaa") # mkdir
os.rmdir("d:\\aaa") # 删除单个空目录
os.listdir("d:\\") # list方式列出当前目录中的内容
os.remove("d:\\a\\b\\c.txt") # 删除某个文件
os.rename("d:\\a\\b\\c.txt", "d:\\a\\b\\f.txt") # 重命名
os.stat("d:\\a\\b\\s.txt") # 文件或目录属性atime mtime ctime等
os.sep # 路径分隔符,Windows为\\Linux为/
os.linesep # 换行符,Windows为\r\nLinux为\n
os.environ # 查看系统的环境变量
os.pathsep # 环境变量的分隔符Windows为分号 Linux为冒号
# 'PATH': 'C:\\ProgramData\\Oracle\\Java\\javapath;C:\\windows\\system32;
os.name # 操作系统名称 Windows为nt
os.system("dir") # 执行操作系统自己的命令
os.path.abspath(__file__) # 获取某文件的绝对路径
os.path.split("d:\\ff\\a.txt") # 返回元祖('d:\\ff', 'a.txt')
os.path.dirname("d:\\ff\\a.txt") # 返回d:\ff
os.path.basename("d:\\ff\\a.txt") # 返回a.txt
os.path.exists("d:\\ff\\a.txt") # 判断文件或目录是否存在
os.path.isabs("d:\\ff\\a\\mj") # True 判断是否为根开始
os.path.isfile("d:\\ff\\222.txt") # 判断是否存在并且为文件
os.path.isdir("d:\\ff\\") # 判断是否存在并且为目录
os.path.join("c:\\", "b", "c.txt") # c:\b\c.txt路径字符串连接
os.path.getatime() # 返回文件或目录atime
os.path.getmtime() # 返回文件或目录的mtime
4.sys模块
import sys sys.path # 返回模块搜索路径,初始化时使用PYTHONPATH环境变量的值
sys.path.append("..") # 添加模块搜索路径
sys.stdout.write(">") # 控制台输出
sys.stdout.flush() # 从缓存刷出去 sys.version # Python解释器版本
sys.argv # ['abc.py脚本名', '参数st', '参数nd', '参数rd']
sys.platform # win32返回操作系统平台名称
sys.exit() # 退出程序,正常退出时exit(0) # python2.7
sys.maxint
sys.stdin.readline()[:-1]
Python退出程序的方式有两种:os._exit(), sys.exit()
1)os._exit() 直接退出 python程序,其后的代码也不会继续执行。
2)sys.exit() 引发一个 SystemExit异常,若没有捕获这个异常,Python解释器会直接退出;捕获这个异常可以做一些额外的清理工作。0为正常退出,其他数值(1-127)为不正常,可抛异常事件供捕获。
exit() 跟 C 语言等其他语言的 exit() 应该是一样的。
os._exit() 调用 C 语言的 _exit() 函数。
__builtin__.exit 是一个 Quitter 对象,这个对象的 __call__ 方法会抛出一个 SystemExit 异常。
一般来说os._exit() 用于在线程中退出
sys.exit() 用于在主线程中退出。
参考:http://blog.csdn.net/taohuaxinmu123/article/details/39669495
5.shutil模块
import shutil f1 = open("a", "r", encoding="utf8")
f2 = open("b", "w", encoding="utf8") shutil.copyfileobj(f1, f2) # 复制文件对象,f1.read(length) f2.write(length)
shutil.copyfile("a", "b") # 输入名字直接复制,内部还是copyfileobj方法
shutil.copymode("a.txt", "b.txt") # Linux系统中,a.txt的rwxrwxrwx权限复制到b.txt上,其他不变
shutil.copystat("a", "b") # Linux中,a的rwx权限,atime,mtime,flags复制到b上,其他不变
shutil.copy("a", "b") # 拷贝a的内容和权限给b,内部实现为先copyfile,再copymode
shutil.copy2("a", "b") # 拷贝a的内容和权限,atime,mtime,flags到b,内部先copyfile,再copystat
shutil.copytree("a", "b/") # 递归复制a目录及其中的所有文件
shutil.rmtree("a") # 递归删除a目录及其所有文件
shutil.move("a", "b") # 递归的移动文件
shutil.make_archive("aa/", "gztar", "/etc/") # /etc目录打包压缩格式为aa.tar.gz
shutil.make_archive("aa/","bztar","/etc/") # /etc目录打包压缩格式为aa.tar.bz2
shutil 对压缩包的处理是调用 ZipFile 和 TarFile 两个模块来进行的,详细:
import zipfile # 压缩
z = zipfile.ZipFile('laxi.zip', 'w')
z.write('a.log')
z.write('data.data')
z.close() # 解压
z = zipfile.ZipFile('laxi.zip', 'r')
z.extractall()
z.close() zipfile 压缩解压
import tarfile # 压缩
tar = tarfile.open('your.tar','w')
tar.add('/Users/wupeiqi/PycharmProjects/bbs2.zip', arcname='bbs2.zip')
tar.add('/Users/wupeiqi/PycharmProjects/cmdb.zip', arcname='cmdb.zip')
tar.close() # 解压
tar = tarfile.open('your.tar','r')
tar.extractall() # 可设置解压地址
tar.close() tarfile 压缩解压
Python学习第二阶段Day2,模块time/datetime、random、os、sys、shutil的更多相关文章
- Python常用模块(time, datetime, random, os, sys, hashlib)
time模块 在Python中,通常有这几种方式来表示时间: 时间戳(timestamp) : 通常来说,时间戳表示的是从1970年1月1日00:00:00开始按秒计算的偏移量.我们运 ...
- 模块、包及常用模块(time/random/os/sys/shutil)
一.模块 模块的本质就是一个.py 文件. 导入和调用模块: import module from module import xx from module.xx.xx import xx as re ...
- python笔记-1(import导入、time/datetime/random/os/sys模块)
python笔记-6(import导入.time/datetime/random/os/sys模块) 一.了解模块导入的基本知识 此部分此处不展开细说import导入,仅写几个点目前的认知即可.其 ...
- day19:常用模块(collections,time,random,os,sys)
1,正则复习,re.S,这个在用的最多,re.M多行模式,这个主要改变^和$的行为,每一行都是新串开头,每个回车都是结尾.re.L 在Windows和linux里面对一些特殊字符有不一样的识别,re. ...
- python基础-7.3模块 configparser logging subprocess os.system shutil
1. configparser模块 configparser用于处理特定格式的文件,其本质上是利用open来操作文件. 继承至2版本 ConfigParser,实现了更多智能特征,实现更有可预见性,新 ...
- Python学习第二阶段Day2(json/pickle)、 shelve、xml、PyYAML、configparser、hashlib模块
1.json/pickle 略. 2.shelve模块 import shelve # shelve 以key value的形式序列化,value为对象 class Foo(object): de ...
- 常用模块之 time,datetime,random,os,sys
time与datetime模块 先认识几个python中关于时间的名词: 时间戳(timestamp):通常来说,时间戳表示的是从1970年1月1日00:00:00开始按秒计算的偏移量.我们运行“ty ...
- Python常用模块(logging&re&时间&random&os&sys&shutil&序列化&configparser&&hashlib)
一. logging(日志模块) 二 .re模块 三. 时间模块 四. random模块 五. os模块 六. sys模块 七. shutil模块 八. 序列化模块(json&pickle&a ...
- time,datetime,random,os,sys,hashlib,logging,configparser,re模块
#-----time模块----- print(help(time)) #打印time帮助文档 print(time.time()) #打印时间戳 1569824501.6265268 time.sl ...
随机推荐
- ViewPager嵌套ViewPager后子ViewPager滑动不正常问题
ViewPager嵌套ViewPager后,滑动事件没法在子ViewPager里面响应. 解决办法是自定义子ViewPager. 以下代码是转载的,经本人测试,可以用!!! 转载地址:http://b ...
- "Hello world" of ML
#!/usr/bin/python import os import pandas as pd from sklearn.datasets import fetch_openml import mat ...
- ubuntu 16.04 Sqoop 安装
1.下载:https://mirrors.tuna.tsinghua.edu.cn/apache/sqoop/1.4.6/ sqoop-1.4.6.bin__hadoop-2.0.4-alpha.ta ...
- C#面向过程之类型转换、算术运算符、关系运算符、逻辑运算符、if-else语句、switch-case、循环结构(while、for)、三元表达式
数据类型转换: int.parse()只能转换string类型的 当参数为null时会报异常int i =Convert.ToInt32(false) 运行结果是0int i =Convert.ToI ...
- Tomcat组件
Tomcat组件 tomcat常用组件 Tomcat的组织结构 Tomcat是一个基于组件的服务器,它的构成组件都是可配置的,其中最外层的给件是CATALINA SERVLET容器,其他的组件按照一定 ...
- [C++ STL] vector使用详解
一.vector介绍: vector(向量): 是一种序列式容器,事实上和数组差不多,但它比数组更优越.一般来说数组不能动态拓展,因此在程序运行的时候不是浪费内存,就是造成越界.而vector正好弥补 ...
- Spring Boot (32) Lock 本地锁
平时开发中,有时会双击提交表单造成重复提交,或者网速比较慢时还没有响应又点击了按钮,我们在开发中必须防止重复提交 一般在前台进行处理,定义个变量,发送请求前判断变量值为true,然后把变量设置为fal ...
- 第2章 JavaScript语法
1.最好的做法是把<script>标签放到html文档的最后,</body>标签之前. 举例: ...... <script src="file.js" ...
- es6之数据结构 set,WeakSet,mapWeakMap
{ let list = new Set(); list.add(1); list.add(2); list.add(1); console.log(list); //Set(2) {1, 2} le ...
- 左耳听风 ARTS Week 001
要求:1.每周至少做一个 leetcode 的算法题 2.阅读并点评至少一篇英文技术文章 3.学习至少一个技术技巧 4.分享一篇有观点和思考的技术文章 1.每周至少做一个 leetcode 的算法题 ...