一 OS模块
对系统进行操作
1.1 popen
可以把运行的结果,这个字符串转化成utf-8这样的编码格式在进行输出
import os
res = os.popen("ifconfig").read()
print(res)
执行
[root@node10 python]# python3 test.py
ens33: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500
inet 192.168.132.140 netmask 255.255.255.0 broadcast 192.168.132.255
inet6 fe80::143b:809:1937:30b7 prefixlen 64 scopeid 0x20<link>
ether 00:0c:29:66:70:ef txqueuelen 1000 (Ethernet)
RX packets 788506 bytes 577669647 (550.9 MiB)
RX errors 0 dropped 0 overruns 0 frame 0
TX packets 723273 bytes 85635044 (81.6 MiB)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0 lo: flags=73<UP,LOOPBACK,RUNNING> mtu 65536
inet 127.0.0.1 netmask 255.0.0.0
inet6 ::1 prefixlen 128 scopeid 0x10<host>
loop txqueuelen 1 (Local Loopback)
RX packets 0 bytes 0 (0.0 B)
RX errors 0 dropped 0 overruns 0 frame 0
TX packets 0 bytes 0 (0.0 B)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0
1.2 listdir()
获取指定文件夹中所有内容的名称列表
import os
lst = os.listdir("/python")
print(lst)
[root@node1
执行
['0209_1.txt',
'0208.txt',
'集合.png',
'集合2.png',
'0208_1.txt',
'0208_2.txt',
'0208_3.txt',
'0208_4.txt',
'集合3.png',
'0208_5.txt',
'0209_2.txt',
'0209_3.txt',
'0209_4.txt',
'test.py',
'0208_7.txt',
'0208_6.txt',
'0209.txt']
1.3 getcwd()
获取当前文件所在的默认路径
import os
res = os.getcwd()
print(res)
执行
[root@node10 python]# python3 test.py
/python
[root@node10 python]# pwd
/python
1.4 对文件的操作
- chdir() 修改当前文件工作的默认路径
- os.chdir("D:\深圳周末三期\L006\lianxi_abc")
- os.mkdir 创建目录(文件夹)
- os.rmdir 删除目录(文件夹)
- os.rmdir("ceshi_111")
- os.rename 对文件,目录重命名
- os.rename("ceshi_222","ceshi333")
- copy(src,dst)
import os
os.mkdir("/tmp/test")
执行
[root@node10 python]# ll /tmp/test/ -d
drwxr-xr-x. 2 root root 6 Nov 25 09:01 /tmp/test/
[root@node10 python]# date
Mon Nov 25 09:02:08 EST 2019
1.5 environ
获取或修改环境变量
import os
res = os.environ
print(res)
执行
environ({'XDG_SESSION_ID': '',
'HOSTNAME': 'node10',
'SELINUX_ROLE_REQUESTED': '',
'TERM': 'xterm',
'SHELL': '/bin/bash',
'HISTSIZE': '',
'SSH_CLIENT': '192.168.132.1 6008 22',
'SELINUX_USE_CURRENT_RANGE': '',
'OLDPWD': '/root',
'SSH_TTY': '/dev/pts/0',
'USER': 'root',
'LS_COLORS': 'rs=0:di=01;34:ln=01;36:mh=00:pi=40;33:so=01;35:do=01;35:bd=40;33;01:cd=40;33;01:or=40;31;01:mi=01;05;37;41:su=37;41:sg=30;43:ca=30;41:tw=30;42:ow=34;42:st=37;44:ex=01;32:*.tar=01;31:*.tgz=01;31:*.arc=01;31:*.arj=01;31:*.taz=01;31:*.lha=01;31:*.lz4=01;31:*.lzh=01;31:*.lzma=01;31:*.tlz=01;31:*.txz=01;31:*.tzo=01;31:*.t7z=01;31:*.zip=01;31:*.z=01;31:*.Z=01;31:*.dz=01;31:*.gz=01;31:*.lrz=01;31:*.lz=01;31:*.lzo=01;31:*.xz=01;31:*.bz2=01;31:*.bz=01;31:*.tbz=01;31:*.tbz2=01;31:*.tz=01;31:*.deb=01;31:*.rpm=01;31:*.jar=01;31:*.war=01;31:*.ear=01;31:*.sar=01;31:*.rar=01;31:*.alz=01;31:*.ace=01;31:*.zoo=01;31:*.cpio=01;31:*.7z=01;31:*.rz=01;31:*.cab=01;31:*.jpg=01;35:*.jpeg=01;35:*.gif=01;35:*.bmp=01;35:*.pbm=01;35:*.pgm=01;35:*.ppm=01;35:*.tga=01;35:*.xbm=01;35:*.xpm=01;35:*.tif=01;35:*.tiff=01;35:*.png=01;35:*.svg=01;35:*.svgz=01;35:*.mng=01;35:*.pcx=01;35:*.mov=01;35:*.mpg=01;35:*.mpeg=01;35:*.m2v=01;35:*.mkv=01;35:*.webm=01;35:*.ogm=01;35:*.mp4=01;35:*.m4v=01;35:*.mp4v=01;35:*.vob=01;35:*.qt=01;35:*.nuv=01;35:*.wmv=01;35:*.asf=01;35:*.rm=01;35:*.rmvb=01;35:*.flc=01;35:*.avi=01;35:*.fli=01;35:*.flv=01;35:*.gl=01;35:*.dl=01;35:*.xcf=01;35:*.xwd=01;35:*.yuv=01;35:*.cgm=01;35:*.emf=01;35:*.axv=01;35:*.anx=01;35:*.ogv=01;35:*.ogx=01;35:*.aac=01;36:*.au=01;36:*.flac=01;36:*.mid=01;36:*.midi=01;36:*.mka=01;36:*.mp3=01;36:*.mpc=01;36:*.ogg=01;36:*.ra=01;36:*.wav=01;36:*.axa=01;36:*.oga=01;36:*.spx=01;36:*.xspf=01;36:',
'SSH_AUTH_SOCK': '/tmp/ssh-VeQHPjKfCf/agent.73524',
'MAIL': '/var/spool/mail/root',
'PATH': '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/root/bin',
'PWD': '/python',
'LANG': 'en_US.UTF-8',
'SELINUX_LEVEL_REQUESTED': '',
'HISTCONTROL': 'ignoredups',
'SHLVL': '',
'HOME': '/root',
'LOGNAME': 'root',
'SSH_CONNECTION': '192.168.132.1 6008 192.168.132.140 22',
'LESSOPEN': '||/usr/bin/lesspipe.sh %s', 'XDG_RUNTIME_DIR': '/run/user/0', '_': '/usr/bin/python3'})
============================================
[root@node10 python]# env
XDG_SESSION_ID=85
HOSTNAME=node10
SELINUX_ROLE_REQUESTED=
TERM=xterm
SHELL=/bin/bash
HISTSIZE=1000
SSH_CLIENT=192.168.132.1 6008 22
SELINUX_USE_CURRENT_RANGE=
OLDPWD=/root
SSH_TTY=/dev/pts/0
USER=root
LS_COLORS=rs=0:di=01;34:ln=01;36:mh=00:pi=40;33:so=01;35:do=01;35:bd=40;33;01:cd=40;33;01:or=40;31;01:mi=01;05;37;41:su=37;41:sg=30;43:ca=30;41:tw=30;42:ow=34;42:st=37;44:ex=01;32:*.tar=01;31:*.tgz=01;31:*.arc=01;31:*.arj=01;31:*.taz=01;31:*.lha=01;31:*.lz4=01;31:*.lzh=01;31:*.lzma=01;31:*.tlz=01;31:*.txz=01;31:*.tzo=01;31:*.t7z=01;31:*.zip=01;31:*.z=01;31:*.Z=01;31:*.dz=01;31:*.gz=01;31:*.lrz=01;31:*.lz=01;31:*.lzo=01;31:*.xz=01;31:*.bz2=01;31:*.bz=01;31:*.tbz=01;31:*.tbz2=01;31:*.tz=01;31:*.deb=01;31:*.rpm=01;31:*.jar=01;31:*.war=01;31:*.ear=01;31:*.sar=01;31:*.rar=01;31:*.alz=01;31:*.ace=01;31:*.zoo=01;31:*.cpio=01;31:*.7z=01;31:*.rz=01;31:*.cab=01;31:*.jpg=01;35:*.jpeg=01;35:*.gif=01;35:*.bmp=01;35:*.pbm=01;35:*.pgm=01;35:*.ppm=01;35:*.tga=01;35:*.xbm=01;35:*.xpm=01;35:*.tif=01;35:*.tiff=01;35:*.png=01;35:*.svg=01;35:*.svgz=01;35:*.mng=01;35:*.pcx=01;35:*.mov=01;35:*.mpg=01;35:*.mpeg=01;35:*.m2v=01;35:*.mkv=01;35:*.webm=01;35:*.ogm=01;35:*.mp4=01;35:*.m4v=01;35:*.mp4v=01;35:*.vob=01;35:*.qt=01;35:*.nuv=01;35:*.wmv=01;35:*.asf=01;35:*.rm=01;35:*.rmvb=01;35:*.flc=01;35:*.avi=01;35:*.fli=01;35:*.flv=01;35:*.gl=01;35:*.dl=01;35:*.xcf=01;35:*.xwd=01;35:*.yuv=01;35:*.cgm=01;35:*.emf=01;35:*.axv=01;35:*.anx=01;35:*.ogv=01;35:*.ogx=01;35:*.aac=01;36:*.au=01;36:*.flac=01;36:*.mid=01;36:*.midi=01;36:*.mka=01;36:*.mp3=01;36:*.mpc=01;36:*.ogg=01;36:*.ra=01;36:*.wav=01;36:*.axa=01;36:*.oga=01;36:*.spx=01;36:*.xspf=01;36:
SSH_AUTH_SOCK=/tmp/ssh-VeQHPjKfCf/agent.73524
MAIL=/var/spool/mail/root
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/root/bin
PWD=/python
LANG=en_US.UTF-8
SELINUX_LEVEL_REQUESTED=
HISTCONTROL=ignoredups
SHLVL=1
HOME=/root
LOGNAME=root
SSH_CONNECTION=192.168.132.1 6008 192.168.132.140 22
LESSOPEN=||/usr/bin/lesspipe.sh %s
XDG_RUNTIME_DIR=/run/user/0
_=/usr/bin/env
1.6 os 模块属性
name 获取系统标识
linux,mac ->posix windows -> nt
import os
print(os.name)
执行
[root@node10 python]# python3 test.py
posix
sep 获取路径分割符号
linux,mac -> / window-> \ *****
import os
print(os.sep)
执行
[root@node10 python]# python3 test.py
/
linesep 获取系统的换行符号
import os
print(repr(os.linesep))
执行
[root@node10 python]# python3 test.py
'\n'
shutil模块
复制文件
import shutil
shutil.copy("test.py","../test1.py")
执行
[root@node10 python]# python3 test.py
[root@node10 python]# cat ../test1.py
import shutil
shutil.copy("test.py","../test1.py")
二 os.path模块
2.1 abspath()
将相对路径转化为绝对路径
. 或者.. 代表的是相对路径
import os
res = os.path.abspath(".")
print(res)
执行
[root@node10 python]# python3 test.py
/python
2.2 basename()
返回文件名部分
import os
strvar = r"/python/0208_2.txt"
res = os.path.basename(strvar)
print(res)
执行
[root@node10 python]# python3 test.py
0208_2.txt
2.3 dirname()
返回路径部分
import os
strvar = r"/python/0208_2.txt"
res = os.path.dirname(strvar)
print(res)
执行
[root@node10 python]# python3 test.py
/python
2.4 split()
将路径拆分成单独的文件部分和路径部分 组合成一个元组
import os
strvar = r"/python/0208_2.txt"
res = os.path.split(strvar)
print(res)
执行
[root@node10 python]# python3 test.py
('/python', '0208_2.txt')
2.5 join()
将多个路径和文件组成新的路径
import os
path1 = "home"
path2 = "test1"
path3 = "test2"
#可以自动通过不同的系统加不同的斜杠 linux / windows \
res = os.path.join(path1,path2,path3)
print(res)
执行
[root@node10 python]# python3 test.py
home/test1/test2
2.6 splitext()
将路径分割为后缀和其他部分
通过splitext 可以快速拿到一个路径中的后缀
import os
strvar = r"/python/test.py"
res = os.path.splitext(strvar)
print(res)
执行
[root@node10 python]# python3 test.py
('/python/test', '.py')
2.7 getsize()
获取文件的大小
import os
strvar = r"/python/test.py"
res = os.path.getsize(strvar)
print(res)
执行
[root@node10 python]# python3 test.py
80
2.8 isdir()和isfile()
isdir()检测路径是否是一个文件夹(路径)
isfile() 检测路径是否是一个文件
import os
strvar = r"/python/"
res = os.path.isdir(strvar)
print(res) res = os.path.isfile(strvar)
print(res)
执行
[root@node10 python]# python3 test.py
True
False
2.9 时间相关
getctime() [windows]文件的创建时间,[linux]权限的改动时间(返回时间戳)
getmtime() 获取文件最后一次修改时间(返回时间戳)
getatime() 获取文件最后一次访问时间(返回时间戳) # 存在系统差异
exists() 检测指定的路径是否存在
isabs() 检测一个路径是否是绝对路径 (了解)
import os
strvar = r"/python/test.py"
print ("getctime")
res = os.path.getctime(strvar)
print(res) import time
res = time.ctime(1557649965)
print (res) print ("getmtime")
res = os.path.getmtime(strvar)
print(res) print ("getatime")
res = os.path.getatime(strvar)
print(res) print ("exists")
res = os.path.exists(strvar)
print(res) print ("isabs")
res = os.path.isabs(strvar)
print(res)
执行
getctime
1574693880.2914786
Sun May 12 04:32:45 2019
getmtime
1574693880.2903953
getatime
1574693882.052988
exists
True
isabs
True
2.10 os.listdir
计算一个文件夹当中所有文件的大小
import os
pathvar = r"/python"
lst = os.listdir(pathvar)
print(lst)
执行
[root@node10 python]# python3 test.py
['0209_1.txt', '0208.txt', '集合.png', '集合2.png', '0208_1.txt', '0208_2.txt', '0208_3.txt', '0208_4.txt', '集合3.png', '0208_5.txt', '0209_2.txt', '0209_3.txt', '0209_4.txt', 'test.py', '0208_7.txt', '0208_6.txt', '0209.txt']
2.11 计算文件大小
1 普通方式
import os
pathvar = r"/python"
lst = os.listdir(pathvar)
print(lst) size = 0
for i in lst:
# 拼接路径 用来判断是文件夹还是文件夹
pathvar2 = os.path.join(pathvar,i)
# 如果是文件夹 执行相应逻辑
if os.path.isdir(pathvar2):
print(i+"是[目录]")
# 如果是文件, 计算文件大小
elif os.path.isfile(pathvar2):
print(i+"是[文件]")
# os.path.getsize 只能计算文件的大小
# 用size 这个变量不停的累加文件大小
size += os.path.getsize(pathvar2) print(size)
执行
['0209_1.txt', '0208.txt', '集合.png', '集合2.png', '0208_1.txt', '0208_2.txt', '0208_3.txt', '0208_4.txt', '集合3.png', '0208_5.txt', '0209_2.txt', '0209_3.txt', '0209_4.txt', 'test.py', '0208_7.txt', '0208_6.txt', '0209.txt']
0209_1.txt是[文件]
0208.txt是[文件]
集合.png是[文件]
集合2.png是[文件]
0208_1.txt是[文件]
0208_2.txt是[文件]
0208_3.txt是[文件]
0208_4.txt是[文件]
集合3.png是[文件]
0208_5.txt是[文件]
0209_2.txt是[文件]
0209_3.txt是[文件]
0209_4.txt是[文件]
test.py是[文件]
0208_7.txt是[文件]
0208_6.txt是[文件]
0209.txt是[文件]
67149
(2) 使用递归来计算文件的总大小
import os
pathvar = "/python"
def getallsize(pathvar):
size = 0
lst = os.listdir(pathvar)
print(lst) #['a.txt', 'b.txt', 'ceshi333']
for i in lst:
pathvar2 = os.path.join(pathvar,i)
if os.path.isdir(pathvar2):
# 模拟鼠标点击进去的动作
'''size += getallsize(pathvar2) 是和上一个代码唯一不一样的地方;'''
size += getallsize(pathvar2) print("是文件夹")
elif os.path.isfile(pathvar2):
size += os.path.getsize(pathvar2)
return size
res = getallsize(pathvar)
print(res)
执行
[root@node10 python]# python3 test.py
['0209_1.txt', '0208.txt', '集合.png', '集合2.png', '0208_1.txt', '0208_2.txt', '0208_3.txt', '0208_4.txt', '集合3.png', '0208_5.txt', '0209_2.txt', '0209_3.txt', '0209_4.txt', 'test.py', '0208_7.txt', '0208_6.txt', '0209.txt']
67383
三 zipfile模块 文件压缩
3.1 压缩文件
import zipfile
# (1)创建一个压缩文件
zf = zipfile.ZipFile("ceshi0209.zip","w",zipfile.ZIP_DEFLATED)
# (2)往压缩包当中存入内容 推荐写入绝对路径
# (路径参数,别名参数)
zf.write(r"/python/test.py","0208_3.txt")
zf.write(r"/python/0209_4.txt","0208_5.txt") # (3)关闭文件
zf.close()
执行
[root@node10 python]# python3 test.py
[root@node10 python]# ll ceshi0209.zip
-rw-r--r--. 1 root root 572 Nov 25 10:18 ceshi0209.zip
3. 2 解压文件
import zipfile
# (1)创建一个压缩文件
zf = zipfile.ZipFile("ceshi0209.zip","w",zipfile.ZIP_DEFLATED)
# (2)往压缩包当中存入内容 推荐写入绝对路径
# (路径参数,别名参数)
zf.write(r"/python/test.py","0208_3.txt")
zf.write(r"/python/0209_4.txt","0208_5.txt") # (3)关闭文件
zf.close() zf = zipfile.ZipFile("ceshi0209.zip","r")
# (1)extractall(路径) 解压所有文件到某个路径下
zf.extractall("/opt/ceshi0209")
zf.close()
(2)extract(文件,路径) 解压指定的某个文件到某个路径下
3.3 追加文件
(支持with写法)
import zipfile
zf = zipfile.ZipFile("ceshi0209.zip","r")
# (2)extract(文件,路径) 解压指定的某个文件到某个路径下
zf.extract("0208_5.txt","/tmp/test")
zf.close() # (3)追加文件(支持with写法)
with zipfile.ZipFile("ceshi0209.zip","a",zipfile.ZIP_DEFLATED) as zf:
# 可以在write写入的时候 , 临时创建文件夹 比如 tmp/555666 这个tmp就是临时文件夹
zf.write(r"/etc/hosts","sudoers")
执行
[root@node10 python]# python3 test.py
[root@node10 python]# ll /tmp/test/
total 4
-rw-r--r--. 1 root root 504 Nov 25 10:41 0208_5.txt
3.4 查看压缩包中的内容
import zipfile# 查看压缩包中的内容
with zipfile.ZipFile("ceshi0209.zip","r") as zf:
res = zf.namelist()
print(res)
执行
[root@node10 python]# python3 test.py
['0208_3.txt', '0208_5.txt', 'etc/sudoers', 'sudoers']