python之路《模块》

1.time模块

FUNCTIONS

asctime(...)

asctime([tuple]) -> string

Convert a time tuple to a string, e.g. ‘Sat Jun 06 16:26:11 1998‘.

When the time tuple is not present, current time as returned by localtime()

is used.

clock(...)

clock() -> floating point number

Return the CPU time or real time since the start of the process or since

the first call to clock().  This has as much precision as the system

records.

ctime(...)

ctime(seconds) -> string

Convert a time in seconds since the Epoch to a string in local time.

This is equivalent to asctime(localtime(seconds)). When the time tuple is

not present, current time as returned by localtime() is used.

get_clock_info(...)

get_clock_info(name: str) -> dict

Get information of the specified clock.

gmtime(...)

gmtime([seconds]) -> (tm_year, tm_mon, tm_mday, tm_hour, tm_min,

tm_sec, tm_wday, tm_yday, tm_isdst)

Convert seconds since the Epoch to a time tuple expressing UTC (a.k.a.

GMT).  When ‘seconds‘ is not passed in, convert the current time instead.

If the platform supports the tm_gmtoff and tm_zone, they are available as

attributes only.

localtime(...)

localtime([seconds]) -> (tm_year,tm_mon,tm_mday,tm_hour,tm_min,

tm_sec,tm_wday,tm_yday,tm_isdst)

Convert seconds since the Epoch to a time tuple expressing local time.

When ‘seconds‘ is not passed in, convert the current time instead.

mktime(...)

mktime(tuple) -> floating point number

Convert a time tuple in local time to seconds since the Epoch.

Note that mktime(gmtime(0)) will not generally return zero for most

time zones; instead the returned value will either be equal to that

of the timezone or altzone attributes on the time module.

monotonic(...)

monotonic() -> float

Monotonic clock, cannot go backward.

perf_counter(...)

perf_counter() -> float

Performance counter for benchmarking.

process_time(...)

process_time() -> float

Process time for profiling: sum of the kernel and user-space CPU time.

sleep(...)

sleep(seconds)

Delay execution for a given number of seconds.  The argument may be

a floating point number for subsecond precision.

strftime(...)

strftime(format[, tuple]) -> string

Convert a time tuple to a string according to a format specification.

See the library reference manual for formatting codes. When the time tuple

is not present, current time as returned by localtime() is used.

Commonly used format codes:

%Y  Year with century as a decimal number.

%m  Month as a decimal number [01,12].

%d  Day of the month as a decimal number [01,31].

%H  Hour (24-hour clock) as a decimal number [00,23].

%M  Minute as a decimal number [00,59].

%S  Second as a decimal number [00,61].

%z  Time zone offset from UTC.

%a  Locale‘s abbreviated weekday name.

%A  Locale‘s full weekday name.

%b  Locale‘s abbreviated month name.

%B  Locale‘s full month name.

%c  Locale‘s appropriate date and time representation.

%I  Hour (12-hour clock) as a decimal number [01,12].

%p  Locale‘s equivalent of either AM or PM.

Other codes may be available on your platform.  See documentation for

the C library strftime function.

strptime(...)

strptime(string, format) -> struct_time

Parse a string to a time tuple according to a format specification.

See the library reference manual for formatting codes (same as

strftime()).

Commonly used format codes:

%Y  Year with century as a decimal number.

%m  Month as a decimal number [01,12].

%d  Day of the month as a decimal number [01,31].

%H  Hour (24-hour clock) as a decimal number [00,23].

%M  Minute as a decimal number [00,59].

%S  Second as a decimal number [00,61].

%z  Time zone offset from UTC.

%a  Locale‘s abbreviated weekday name.

%A  Locale‘s full weekday name.

%b  Locale‘s abbreviated month name.

%B  Locale‘s full month name.

%c  Locale‘s appropriate date and time representation.

%I  Hour (12-hour clock) as a decimal number [01,12].

%p  Locale‘s equivalent of either AM or PM.

Other codes may be available on your platform.  See documentation for

the C library strftime function.

time(...)

time() -> floating point number

Return the current time in seconds since the Epoch.

Fractions of a second may be present if the system clock provides them.

2.random

详细信息

1 help(random)

我们先分析几个常见的

# 1.随机数0到1之间取
print(random.random())
# 2.随机整数
print(random.randint(0, 2))
# 3.随机整数左闭右开
print(random.randrange(0, 6))
# 随机选值  字符穿数组元组都行
print(random.choice(‘hello‘))
# 规定长度去浮点数
print(random.uniform(0, 9))
# 洗牌功能
name = [1, 2, 3, 4, 5, 6]
random.shuffle(name)
print(name)

现在我将我们学的内容实现一个现实生活的问题

出现随机验证码

check_code = ‘‘
for i in range(0, 4):
    temp = random.randrange(0, 4)
    if i == temp:
        code1 = random.randint(0, 9)   # 当i与temp相同时随机数在0到九之间
    else:
        code1 = chr(random.randint(97, 122))  # 否则就为字母
    check_code += str(code1)
print(check_code)

3.os模块

#OS模块

#os模块就是对操作系统进行操作,使用该模块必须先导入模块:
import os

#getcwd() 获取当前工作目录(当前工作目录默认都是当前文件所在的文件夹)
result = os.getcwd()
print(result)

#chdir()改变当前工作目录
os.chdir(‘/home/sy‘)
result = os.getcwd()
print(result)

open(‘02.txt‘,‘w‘)

#操作时如果书写完整的路径则不需要考虑默认工作目录的问题,按照实际书写路径操作
open(‘/home/sy/下载/02.txt‘,‘w‘)

#listdir() 获取指定文件夹中所有内容的名称列表
result = os.listdir(‘/home/sy‘)
print(result)

#mkdir()  创建文件夹
#os.mkdir(‘girls‘)
#os.mkdir(‘boys‘,0o777)

#makedirs()  递归创建文件夹
#os.makedirs(‘/home/sy/a/b/c/d‘)

#rmdir() 删除空目录
#os.rmdir(‘girls‘)

#removedirs 递归删除文件夹  必须都是空目录
#os.removedirs(‘/home/sy/a/b/c/d‘)

#rename() 文件或文件夹重命名
#os.rename(‘/home/sy/a‘,‘/home/sy/alibaba‘
#os.rename(‘02.txt‘,‘002.txt‘)

#stat() 获取文件或者文件夹的信息
#result = os.stat(‘/home/sy/PycharmProject/Python3/10.27/01.py)
#print(result)

#system() 执行系统命令(危险函数)
#result = os.system(‘ls -al‘)  #获取隐藏文件
#print(result)

#环境变量
‘‘‘
环境变量就是一些命令的集合
操作系统的环境变量就是操作系统在执行系统命令时搜索命令的目录的集合
‘‘‘
#getenv() 获取系统的环境变量
result = os.getenv(‘PATH‘)
print(result.split(‘:‘))

#putenv() 将一个目录添加到环境变量中(临时增加仅对当前脚本有效)
#os.putenv(‘PATH‘,‘/home/sy/下载‘)
#os.system(‘syls‘)

#exit() 退出终端的命令

#os模块中的常用值
#curdir  表示当前文件夹   .表示当前文件夹  一般情况下可以省略
print(os.curdir)

#pardir  表示上一层文件夹   ..表示上一层文件夹  不可省略!
print(os.pardir)

#os.mkdir(‘../../../man‘)#相对路径  从当前目录开始查找
#os.mkdir(‘/home/sy/man1‘)#绝对路径  从根目录开始查找

#name 获取代表操作系统的名称字符串
print(os.name) #posix -> linux或者unix系统  nt -> window系统

#sep 获取系统路径间隔符号  window ->\    linux ->/
print(os.sep)

#extsep 获取文件名称和后缀之间的间隔符号  window & linux -> .
print(os.extsep)

#linesep  获取操作系统的换行符号  window -> \r\n  linux/unix -> \n
print(repr(os.linesep))

#导入os模块
import os

#以下内容都是os.path子模块中的内容

#abspath()  将相对路径转化为绝对路径
path = ‘./boys‘#相对
result = os.path.abspath(path)
print(result)

#dirname()  获取完整路径当中的目录部分  &  basename()获取完整路径当中的主体部分
path = ‘/home/sy/boys‘
result = os.path.dirname(path)
print(result)

result = os.path.basename(path)
print(result)

#split() 将一个完整的路径切割成目录部分和主体部分
path = ‘/home/sy/boys‘
result = os.path.split(path)
print(result)

#join() 将2个路径合并成一个
var1 = ‘/home/sy‘
var2 = ‘000.py‘
result = os.path.join(var1,var2)
print(result)

#splitext() 将一个路径切割成文件后缀和其他两个部分,主要用于获取文件的后缀
path = ‘/home/sy/000.py‘
result = os.path.splitext(path)
print(result)

#getsize()  获取文件的大小
#path = ‘/home/sy/000.py‘
#result = os.path.getsize(path)
#print(result)

#isfile() 检测是否是文件
path = ‘/home/sy/000.py‘
result = os.path.isfile(path)
print(result)

#isdir()  检测是否是文件夹
result = os.path.isdir(path)
print(result)

#islink() 检测是否是链接
path = ‘/initrd.img.old‘
result = os.path.islink(path)
print(result)

#getctime() 获取文件的创建时间 get create time
#getmtime() 获取文件的修改时间 get modify time
#getatime() 获取文件的访问时间 get active time

import time

filepath = ‘/home/sy/下载/chls‘

result = os.path.getctime(filepath)
print(time.ctime(result))

result = os.path.getmtime(filepath)
print(time.ctime(result))

result = os.path.getatime(filepath)
print(time.ctime(result))

#exists() 检测某个路径是否真实存在
filepath = ‘/home/sy/下载/chls‘
result = os.path.exists(filepath)
print(result)

#isabs() 检测一个路径是否是绝对路径
path = ‘/boys‘
result = os.path.isabs(path)
print(result)

#samefile() 检测2个路径是否是同一个文件
path1 = ‘/home/sy/下载/001‘
path2 = ‘../../../下载/001‘
result = os.path.samefile(path1,path2)
print(result)

#os.environ 用于获取和设置系统环境变量的内置值
import os
#获取系统环境变量  getenv() 效果
print(os.environ[‘PATH‘])

#设置系统环境变量 putenv()
os.environ[‘PATH‘] += ‘:/home/sy/下载‘
os.system(‘chls‘)

4.sys模块

5.shutil 拷贝文件用的 压缩也可以

原文地址:https://www.cnblogs.com/BookMiki/p/9697324.html

时间: 2024-07-31 06:07:58

python之路《模块》的相关文章

Python之路【第十七篇】:Django【进阶篇 】

Python之路[第十七篇]:Django[进阶篇 ] Model 到目前为止,当我们的程序涉及到数据库相关操作时,我们一般都会这么搞: 创建数据库,设计表结构和字段 使用 MySQLdb 来连接数据库,并编写数据访问层代码 业务逻辑层去调用数据访问层执行数据库操作 import MySQLdb def GetList(sql): db = MySQLdb.connect(user='root', db='wupeiqidb', passwd='1234', host='localhost')

Python之路【第九篇】:Python操作 RabbitMQ、Redis、Memcache、SQLAlchemy

Python之路[第九篇]:Python操作 RabbitMQ.Redis.Memcache.SQLAlchemy Memcached Memcached 是一个高性能的分布式内存对象缓存系统,用于动态Web应用以减轻数据库负载.它通过在内存中缓存数据和对象来减少读取数据库的次数,从而提高动态.数据库驱动网站的速度.Memcached基于一个存储键/值对的hashmap.其守护进程(daemon )是用C写的,但是客户端可以用任何语言来编写,并通过memcached协议与守护进程通信. Memc

七日Python之路--第十二天(Django Web 开发指南)

<Django Web 开发指南>.貌似使用Django1.0版本,基本内容差不多,细读无妨.地址:http://www.jb51.net/books/76079.html (一)第一部分 入门 (1)内置数字工厂函数 int(12.34)会创建一个新的值为12的整数对象,而float(12)则会返回12.0. (2)其他序列操作符 连接(+),复制(*),以及检查是否是成员(in, not in) '**'.join('**')   或  '***%s***%d' % (str, int)

七日Python之路--第九天

众所周知,代码这东西不是看出来的.程序这东西只哟一个标准. 下面找点开源的东西看看,学习一下大婶们的犀利编码...... 推荐一下: 虽然有点老了:http://www.iteye.com/topic/405150,还有就是GitHub上面搜索一下Django就能出来很多,当然还有OSChina.只是有个问题,就是Django版本不同,具体的内容可能会有些不同,但大概还是相同的.领略即可,然后书写自己的代码. 首要的还是官方文档. 看着还是有些难度的.偶然发现一个不错的Blog:http://w

Python之路【第三篇】:Python基础(二)

Python之路[第三篇]:Python基础(二) 内置函数 一 详细见python文档,猛击这里 文件操作 操作文件时,一般需要经历如下步骤: 打开文件 操作文件 一.打开文件 1 文件句柄 = file('文件路径', '模式') 注:python中打开文件有两种方式,即:open(...) 和  file(...) ,本质上前者在内部会调用后者来进行文件操作,推荐使用 open. 打开文件时,需要指定文件路径和以何等方式打开文件,打开后,即可获取该文件句柄,日后通过此文件句柄对该文件操作.

Python之路【第二篇】:Python基础(一)

Python之路[第二篇]:Python基础(一) 入门知识拾遗 一.作用域 对于变量的作用域,执行声明并在内存中存在,该变量就可以在下面的代码中使用. 1 2 3 if 1==1:     name = 'wupeiqi' print  name 下面的结论对吗? 外层变量,可以被内层变量使用 内层变量,无法被外层变量使用 二.三元运算 1 result = 值1 if 条件 else 值2 如果条件为真:result = 值1如果条件为假:result = 值2 三.进制 二进制,01 八进

Python之路【第十九篇】:爬虫

Python之路[第十九篇]:爬虫 网络爬虫(又被称为网页蜘蛛,网络机器人,在FOAF社区中间,更经常的称为网页追逐者),是一种按照一定的规则,自动地抓取万维网信息的程序或者脚本.另外一些不常使用的名字还有蚂蚁.自动索引.模拟程序或者蠕虫. Requests Python标准库中提供了:urllib.urllib2.httplib等模块以供Http请求,但是,它的 API 太渣了.它是为另一个时代.另一个互联网所创建的.它需要巨量的工作,甚至包括各种方法覆盖,来完成最简单的任务. import

Python之路【第七篇】:线程、进程和协程

Python之路[第七篇]:线程.进程和协程 Python线程 Threading用于提供线程相关的操作,线程是应用程序中工作的最小单元. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 #!/usr/bin/env python # -*- coding:utf-8 -*- import threading import time   def show(arg):     time.sleep(1)     print 'thread'+str(arg)   for i in

Python之路【第八篇】:堡垒机实例以及数据库操作

Python之路[第八篇]:堡垒机实例以及数据库操作 堡垒机前戏 开发堡垒机之前,先来学习Python的paramiko模块,该模块机遇SSH用于连接远程服务器并执行相关操作 SSHClient 用于连接远程服务器并执行基本命令 基于用户名密码连接: + import paramiko transport = paramiko.Transport(('hostname', 22)) transport.connect(username='wupeiqi', password='123') ssh

Python之路【第十六篇】:Django【基础篇】

Python之路[第十六篇]:Django[基础篇] Python的WEB框架有Django.Tornado.Flask 等多种,Django相较与其他WEB框架其优势为:大而全,框架本身集成了ORM.模型绑定.模板引擎.缓存.Session等诸多功能. 基本配置 一.创建django程序 终端命令:django-admin startproject sitename IDE创建Django程序时,本质上都是自动执行上述命令 其他常用命令: python manage.py runserver