python—os模块、时间模块

os模块
作用:os模块是python标准库中的一个用于访问操作系统功能的模块, os模块提供了其他操作系统接口,可以实现跨平台访问。
使用:
1 . 返回操作系统类型 :os.name
值为:posix 是linux操作系统
值为:nt 是windows操作系统

import os
print(os.name)
print('Linux' if os.name == 'posix' else 'Windows')运行结果为:
posix
Linux         

2 . 操作系统的详细信息

import osinfo = os.uname()
print(info)
print(info.sysname)
print(info.nodename)运行结果:
posix.uname_result(sysname='Linux', nodename='foundation5.ilt.example.com', release='3.10.0-514.el7.x86_64', version='#1 SMP Wed Oct 19 11:24:13 EDT 2016', machine='x86_64')
Linux
foundation5.ilt.example.com

3.系统的环境变量

import osprint(os.environ)

通过key值获取环境变量对应的value值

import os
print(os.environ.get('PATH'))运行结果:
/usr/local/bin:/usr/local/sbin:/usr/bin:/usr/sbin:/bin:/sbin:/home/kiosk/.local/bin:/home/kiosk/bin

4.判断是否是绝对路径
只会判断路径,并不会判断目录或者文件是否存在

import os
print(os.path.isabs('/tmp/ffff'))
print(os.path.isabs('hello.jog'))运行结果:
True
False

5.生成绝对路径

import os
print(os.path.abspath('hello.png'))
print(os.path.join(os.path.abspath('.'),'hello.jpg'))
print(os.path.join('/home/kiosk','hello.jpg'))运行结果:
home/kiosk/PycharmProjects/20190523/hello.png
/home/kiosk/PycharmProjects/20190523/hello.jpg
/home/kiosk/hello.jpg

6.获取目录或文件名

import os
filename = '/home/dd/20190523/day06/hello.jpg'
print(os.path.basename(filename))
print(os.path.dirname(filename))运行结果:
hello.jpg
/home/dd/20190523/day06

7.创建和删除目录
os.mkdir()创建
os.makedirs()递归创建
os.rmdir()删除
不能递归删除目录

8.创建文件 删除文件
os.mknod()创建
os.remove()删除

9.文件重命名

 import osos.rename('data.txt','data1.txt')

10.判断文件或目录是否存在

import os
print(os.path.exists('ips.txtyyyy'))

11.分离后缀名和文件名

import os
print(os.path.splitext('hello.jpg'))运行结果:
('hello', '.jpg')

12.将目录名和文件名分离

import os
print(os.path.split('/tmp/hello/hello.jpg'))运行结果:
('/tmp/hello', 'hello.jpg')

练习题:
1 . 在当前目录新建目录img, 里面包含多个文件, 文件名各不相同(X4G5.png)

import os
import random
import string
def str_name():"""生成文件名称"""name_li = random.sample(string.ascii_letters+string.digits,4)return ''.join(name_li)+'.png'
def create_file():os.mkdir('img')name = {str_name() for i in range(100)}for k in name:filename = os.path.join('img', k)os.mknod(filename)
create_file()

2 . 将当前img目录所有以.png结尾的后缀名改为.jpg

import os
def change(dirname,old_suffix,new_suffix):filename_li = [name for name in os.listdir(dirname) if name.endswith(old_suffix)]for filename in filename_li:oldname = os.path.join(dirname, filename)newname = os.path.join(dirname, os.path.splitext(filename)[0] + new_suffix)os.rename(oldname, newname)
change('img','.png','jpg')

时间模块
python中时间表示的类型

1.时间戳:即从1970年1月1日到现在,单位是秒

import timeprint(time.time())运行结果:
1560407829.1201346

2.字符串时间

import timeprint(time.ctime())运行结果:
Thu Jun 13 14:37:59 2019

3.元组类型的时间

import timeprint(time.localtime())
info = time.localtime()
print(info.tm_year)
print(info.tm_mon)运行结果:
time.struct_time(tm_year=2019, tm_mon=6, tm_mday=13, tm_hour=14, tm_min=38, tm_sec=56, tm_wday=3, tm_yday=164, tm_isdst=0)
2019
6

文件的时间戳:
系统中文件存在三个时间戳:
atime:读取一次文件的内容,该时间便会更新。比如对这个文件使用less命令或者more命令。(ls、stat这样的命令不会修改文件访问时间)
mtime:对文件内容修改一次便会更新该时间。例如使用vim等工具更改了文件内容并保存后,文件修改时间发生变化。通过ls –l列出的时间便是这个时间。要想看到文件访问时间可使用ls –ul命令。
ctime:更改文件的属性便会更新该时间,比如使用chmod命令更改文件属性,或者执行其他命令时隐式的附带更改了文件的属性若文件大小等。
stat 文件名称 #查看文件的时间戳
touch 文件名称 #同时修改文件的三个时间戳

[kiosk@foundation5 Desktop]$ stat haha File: ‘haha’Size: 15168     	Blocks: 32         IO Block: 4096   regular file
Device: 801h/2049d	Inode: 137896031   Links: 1
Access: (0755/-rwxr-xr-x)  Uid: ( 1000/   kiosk)   Gid: ( 1000/   kiosk)
Access: 2019-06-13 08:52:55.289390893 +0800        ### atime
Modify: 2019-06-08 14:17:57.996665181 +0800	       ### mtime
Change: 2019-06-08 14:17:58.043666378 +0800        ### ctimeBirth: -[kiosk@foundation5 Desktop]$ touch haha
[kiosk@foundation5 Desktop]$ stat haha File: ‘haha’Size: 15168     	Blocks: 32         IO Block: 4096   regular file
Device: 801h/2049d	Inode: 137896031   Links: 1
Access: (0755/-rwxr-xr-x)  Uid: ( 1000/   kiosk)   Gid: ( 1000/   kiosk)
Access: 2019-06-13 14:46:28.080062542 +0800       
Modify: 2019-06-13 14:46:28.080062542 +0800
Change: 2019-06-13 14:46:28.080062542 +0800   ## 三个时间戳全部更改Birth: -

常用的时间转换:
1 . 把元组的时间转换为时间戳

import time
tuple_time = time.localtime()
print(tuple_time)
print(time.mktime(tuple_time))

2 . 把元组时间转换成字符串时间

import time
tuple_time = time.localtime()
print(time.strftime('%m-%d',tuple_time))
print(time.strftime('%Y-%m-%d',tuple_time))
print(time.strftime('%T',tuple_time))
print(time.strftime('%F',tuple_time))

3 . 将时间戳类型转换成为字符串时间

import os
import time
pwd_time = os.path.getctime('/etc/passwd')
print('pwd_time',pwd_time)
print(time.ctime(pwd_time))

4 . 将时间戳转换为元组

import os
import time
pwd_time = os.path.getctime('/etc/passwd')
tuple_time = time.localtime()
print(time.localtime(pwd_time))

5 . 将元组类型转换为时间戳

import timetuple_time = time.localtime()
print(time.mktime(tuple_time))

示例:
1 . 根据指定的格式把一个时间字符串解析为时间元组

import times = '2019-6-6'
print(time.strptime(s,'%Y-%m-%d'))
s_time = '09:00:00'
print(time.strptime(s_time,'%H:%M:%S'))

2 . datetime

import os
from datetime import date
from datetime import datetime
from datetime import timedeltaprint(date.today())
print(datetime.now())
# 计算三天前的时间和三天后的时间
d = date.today()
delta = timedelta(days=31)
print(d + delta)
print(d - delta)# 计算两个小时前的时间和两个小时后的时间
now_hour = datetime.now()
delta = timedelta(hours=2)
print(now_hour - delta)
print(now_hour + delta)# 返回两个时间,计算两个时间之间的时间差
now_time = datetime.now()
print(now_time)
pwd_time = os.path.getmtime('/etc/passwd')
print(pwd_time)
pwd_time_obj = datetime.fromtimestamp(pwd_time)
print(pwd_time_obj)
delta = now_time - pwd_time_obj
print(delta)

需求:
1.获取当前主机信息, 包含操作系统名, 主机名,
内核版本, 硬件架构等
2.获取开机时间和开机时长;
3.获取当前登陆用户

import os
import psutil
from datetime import datetimeprint('主机信息'.center(50,'*'))
info = os.uname()
print("""操作系统:%s主机名称:%s内核版本:%s硬件架构:%s"""%(info.sysname,info.nodename,info.release,info.machine)
)print('开机信息'.center(50,'*'))
boot_time = psutil.boot_time() #返回一个时间戳
# 将时间戳转化为datetime类型的时间
boot_time_obj = datetime.fromtimestamp(boot_time)
#print(type(boot_time_obj))
now_time = datetime.now()
#print(now_time)
delta_time = datetime.now()
delta_time = now_time - boot_time_obj
#print(delta_time)
#print(type(delta_time))print('开机时间:',boot_time_obj)
# str是为了将时间对象转换为字符串,实现分离
print('当前时间:',str(now_time).split('.')[0])
print('开机时长:',str(delta_time).split('.')[0])print('当前登陆用户'.center(50,'*'))
login_user = psutil.users()
print(login_user)
# info = psutil.users()[0]
# print(info.name)

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/542081.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

kotlin键值对数组_Kotlin程序检查数组是否包含给定值

kotlin键值对数组Given an array and an element, we have to check whether array contains the given element or not. 给定一个数组和一个元素,我们必须检查数组是否包含给定的元素。 Example: 例: Input:arr [34, 56, 7, 8, 21, 0, -6]element to…

enter sleep mode黑屏怎么解决_【linux】 不要再暴力关机了,讲讲我最近遇到的问题和完美解决方案...

欢迎关注我的个人公众号:AI蜗牛车前言结束了每天的紧张的工作,这两天真的有些肝。这两天打打字,突然感觉手指头疼起来了,想意识到成天打了十多个小时的键盘, 手指头都疲劳了 之后这两天基本上除了基本的吃睡&#xff…

重复T次的LIS的dp Codeforces Round #323 (Div. 2) D

http://codeforces.com/contest/583/problem/D 原题:You are given an array of positive integers a1, a2, ..., an  T of length n  T. We know that for any i > n it is true that ai  ai - n. Find the length of the longest non-decreasing …

微擎pc 导入前缀_段覆盖前缀| 8086微处理器

微擎pc 导入前缀As we already know that the effective address is calculated by appending the segment registers value and adding up the value of the respective offset. But what if we want to choose some other offset than the assigned one. 众所周知&#xff0…

python—面向对象

面向过程 面向对象: 面向过程:—侧重于怎么做? 1.把完成某一个需求的 所有步骤 从头到尾 逐步实现 2.根据开发要求,将某些功能独立的代码封装成一个又一个函数 3.最后完成的代码,就是顺序的调用不同的函数 特点&#…

5中bug vue_苹果官网出BUG!这些都只要一两百元

近日,有网友在网上反馈称,他发现苹果官网商城出现了BUG!众多上千元的产品,BUG价只需一两百元。比如Shure MOTIV MV88 Digital立体声电容式麦克风配件。正常售价1288元,而BUG后的价格是235元。UBTECH Jimu Astrobot Cos…

常用压缩,解压与打包

常用压缩格式: .zip .zg .bz2 .tar.gz .tar.bz2.zip格式压缩zip 压缩文件名 源文件#压缩文件注:压缩文件名写.zip后缀是为了标记该文件的压缩类型,方便管理。注:在压缩时有压缩格式转换,所以当源文件很小时&#xff0c…

css禁用选中文本_使用CSS禁用文本选择突出显示

css禁用选中文本Introduction: 介绍: Texts are the most fundamental elements of any websites or web pages, they form the basis of the web pages or websites because if you don’t write something that you will not be able to present anything. There…

CDN加速实现—varnish

CDN介绍: 1 . 对cdn的理解: CDN的全称是(Content Delivery Network),即内容分发网络;加速器,反向代理缓存。CDN系统能够实时的根据网络流量和各节点的连接,负载状况以及到用户的举例…

3dmax如何拆分模型_3dmax制作装饰柜1

大家好,今天我来为大家讲解一下如何利用3dmax制作装饰柜。我们需要制作装饰柜模型,当我们为它添加一个材质后,它就是这样的效果。单击创建,选择图形,对象为样条线,选择矩形在场景中进行创建。单击修改&…

TODO:macOS上ThinkPHP5和Semantic-UI集成

TODO:macOS上ThinkPHP5和Semantic-UI集成1. 全局安装 (on OSX via homebrew)Composer 是 homebrew-php 项目的一部分2. 把Xcode升级到8.1后继续安装Composer3. 使用composer创建TP5项目MWL-Dispatchcomposer create-project topthink/think MWL-Dispatch4. 配置apac…

np.expm1_JavaScript中带有示例的Math.expm1()方法

np.expm1JavaScript | Math.expm1()方法 (JavaScript | Math.expm1() Method) Math operations in JavaScript are handled using functions of math library in JavaScript. In this tutorial on Math.expm1() method, we will learn about the expm1() method and its workin…

距离传感器控制灯泡代码_生迪全彩智能 LED 灯泡体验评测

市面上大多数智能灯具无外乎智能控制,冷暖标准区间的简单调光,仅仅满足我们日常照明之外,似乎用处不多。如果有一款能在自己房间制造多彩氛围的灯泡就好了。这次有幸体验到了华为智能家居生态链产品生迪全彩智能 LED 灯泡,才发现彩…

mysql启动与关闭(手动与自动)

手动管理mysql的启动与关闭 [rootmysql ~]# service mysql start --手动启动mysqlStarting MySQL. SUCCESS![rootmysql ~]# service mysql stop --手动关闭mysql Shutting down MySQL.. SUCCESS! [rootmysql ~]# mysqld --verbose --help --查看MySQL的默认参数的具体值 如果每…

JavaScript中带有示例的Math.round()方法

JavaScript | Math.round()方法 (JavaScript | Math.round() Method) Math.round() is a function in math library of JavaScript that is used to round the given number floating-point number to the nearest integer value. Math.round()是JavaScript数学库中的函数&…

内部导线拉力测试_珠海后环回收试验机现金支付拉力试验机回收和谐温馨的环境...

珠海后环回收试验机现金支付拉力试验机回收和谐温馨的环境深圳富兴二手设备回收,拉力试验机回收,恒温恒湿箱回收,恒温恒湿试验箱回收,恒温恒湿培养箱回收,高低温试验箱回收,高低温冲击试验机回收&#xff0…

lvs负载均衡—ldirectord(DR模式的健康检查)

作用: 健康检查对企业而言也是由为重要,在生活中,有时候访问网页访问不到,就会跳出来一些图形告诉你访问失败,这就是健康检查的作用,当服务器都挂掉的时候,告诉你暂时访问不了。 ldirectord是后…

Reactor by Example--转

原文地址:https://www.infoq.com/articles/reactor-by-example Key takeaways Reactor is a reactive streams library targeting Java 8 and providing an Rx-conforming APIIt uses the same approach and philosophy as RxJava despite some API differencesIt i…

springboot项目后台运行关闭_springboot项目在服务器上部署过程(新手教程)

环境:服务器系统:ubuntu16jdkmysql工具 xshell6下载地址:https://www.netsarang.com/download/down_form.html?code622&downloadType0&licenseType1xftp6下载地址:https://www.netsarang.com/download/down_form.html?c…

如何在React Native中使用文本输入组件?

You know, an app becomes more authentic and professional when there is the interaction between the app and the user. 您知道,当应用程序与用户之间存在交互时,该应用程序将变得更加真实和专业。 The text input component in react-native brin…