0729Python总结-os 对系统进行操作,os 和 shutil,os.path 路径模块,计算文件夹大小,tarfile 压缩模块 .tar | .tar.gz | .tar.bz2

一.os 对系统进行操作

import os

system() 在Python中执行系统命令

popen() 执行系统命令返回对象,通过read方法读出字符串(防止字符串乱码,使用popen进行操作)

obj = os.popen("ifconfig")  # 显示的时候,按照utf-8进行转换,默认Windows是gbk的编码集
res = obj.read()
print(res)

listdir() 获取指定文件夹中所有内容的名称列表

lst = os.listdir(".")  # . 当前目录
lst = os.listdir("..")  # .. 上一级目录
lst = os.listdir("/home/cuiwenjun/")
print(lst)

getcwd() 获取当前文件夹所在的默认路径(单纯的路径)

res = os.getcwd()
print(res)  # /mnt/hgfs/python_gx/day19

路径 + 文件

print(__file__)  # /mnt/hgfs/python_gx/day19/1-2os对系统进行操作.py

chdir() 修改当前文件工作的默认路径

os.chdir("/home/cuiwenjun/mywork")
# os.system("mkdir ceshi100")
os.system("rm -rf ceshi100")

environ 提取或修改环境变量

print(os.environ["PATH"])
os.environ["PATH"] += ":/home/cuiwenjun/mywork"
os.system("cuiwenjun")
通过系统的环境变量path,自动找该命令的路径
[Windows]
1.右键qq -> 看一眼当前qq所在的路径,把路径复制一下
2.右键我的电脑 -> 属性 -> 高级系统设置 -> 环境变量 -> 编辑Path环境变量 ->新建添加一下即可
3.打开cmd ->QQScLauncher.exe  ->通过命令调用qq

[Linux]
1.在/home/cuiwenjun -> mkdir mywork -> touch cuiwenjun
2.nano cuiwenjun -> ifconfig
3.chmod 777 cuiwenjun -> ./cuiwenjun -> 产生效果
4.把cuiwenjun所在的路径添加到Linux的环境变量path中(系统可以自动找cuiwenjun命令的路径)
5.os.environ["PATH"] += ":/home/cuiwenjun/mywork"
6.os.system("cuiwenjun")
–os 模块属性

name

获取系统标识 Linux,mac ->posix Windows -> nt *
print(os.name)

sep

获取路径分割符号 Linux,mac -> / Windows -> \ ***
print(os.sep)

linesep

获取系统的换行符号 Linux,mac -> \n Windows ->\r\n 或\n *
print(repr(os.linesep))

二.os 和 shutil

import os
os.chdir("/home/cuiwenjun/mywork")

1.os -> 新建/删除

os.mknod 创建文件

os.mknod(“1.txt”)

os.remove 删除文件

remove(“1.txt”)

os.mkdir 创建目录(文件夹)

os.mkdir(“ceshi100”)

os.rmdir 删除目录(文件夹)

os.rmdir(“ceshi100”)

os.rename 对文件,目录重命名

os.rename(“111.txt”, “123.py”)

os.makedirs 递归创建文件夹

os.makedirs(“a/b/c/d/e”)

2.shutil -> 复制/移动

import shutil

(1)单纯复制文件的内容

copyfileobj(fsrc, fdst[, length=16*1024]) 复制文件(length的单位是字符(表达一次读多少字符))

fp1 = open("123.py", mode="r", encoding="utf-8")
fp2 = open("lianxi1.php", mode="w", encoding="utf-8")
shutil.copyfileobj(fp1, fp2)

copyfile(src, dst) 单纯的仅复制文件内容,底层调用了copyfileobj ***

shutil.copyfile("lianxi1.php", "lianxi2.py")
(2)单纯复制权限

copymode(src, dst) 单纯的仅复制权限,不包含内容(虚拟机共享目录都是777)

shutil.copymode("123.py", "456.py")

copystat(src, dst) 复制所有状态信息,包括权限,组,用户,修改时间等,不包括内容 ***

shutil.copystat("123.py", "lianxi2.py")
(3)复制文件内容 + 文件权限

copy(src, dst) 复制文件权限和内容 ***

shutil.copy("456.py", "lianxi3.html")

copy2(src, dst) 复制文件权限和内容,还包括权限,组,用户,时间等 ***

shutil.copy2("456.py", "lianxi4.css")
(4)删除/移动(文件和文件夹) ***

copytree(src, dst) 拷贝文件夹里所有内容(递归拷贝)

shutil.copytree("lianxi100", "lianxi101")

rmtree(path) 删除当前文件夹及其中所有内容(递归删除)

shutil.rmtree("lianxi101")

move(path1, path2) 移动文件或者文件夹

shutil.move("lianxi1.php", "..")
shutil.move("lianxi100", "../lianxi10000")  # 移动并改名

三.os.path 路径模块

import os

basename() 返回文件名部分 *

strvar = "/home/cuiwenjun/mywork/ceshi110.html"
res = os.path.basename(strvar)
print(res)  # ceshi110.html

dirname() 返回路径部分 *

res = os.path.dirname(strvar)
print(res)  # /home/cuiwenjun/mywork

split() 将路径拆分成单独的文件部分和路径部分 组合成一个元组

tup = os.path.split(strvar)
print(tup)  # ('/home/cuiwenjun/mywork', 'ceshi110.html')

join() 将多个路径和文件组成新的路径 可以自动通过不同的系统加不同的斜杠 Linux / Windows \ ***

path1 = "ceshi1"
path2 = "cuiwenjun"
path3 = "lianxi1.py"
pathvar = path1 + os.sep + path2 + os.sep + path3  # ceshi1/cuiwenjun/lianxi1.py
# pathvar = path1 + "/" + path2 + "/" + path3
pathvar = os.path.join(path1, path2, path3)
print(pathvar)

splitext() 将路径分割为后缀和其他部分(了解)

strvar = "/home/cuiwenjun/mywork/ceshi110.html"
res = os.path.splitext(strvar)
print(res)  # ('/home/cuiwenjun/mywork/ceshi110', '.html')

可以使用split切割出后缀

lst = strvar.split(".")
print(lst[-1])  # html

getsize() 获取文件的大小 ***

# res = os.path.getsize("1.py")
# 文件夹不能计算
res = os.path.getsize("os")
print(res)

isdir() 检测路径是否是一个文件夹 *

strvar = "/home/cuiwenjun/mywork/cuiwenjun"
res = os.path.isdir(strvar)
print(res)

isfile() 检测路径是否是一个文件 *

strvar = "/home/cuiwenjun/mywork/cuiwenjun"
res = os.path.isfile(strvar)
print(res)

islink() 检测路径是否是一个链接 *

strvar = "/home/cuiwenjun/mywork/cuiwenjun"
res = os.path.islink(strvar)
print(res)

os.chdir("/home/cuiwenjun/mywork")
“”“stat 文件 查看当前文件的时间属性”""
import time

getctime() [Windows]文件的创建时间,[Linux]权限的改动时间(返回时间戳) *

res = os.path.getctime("123.py")

getmtime() 获取文件最后一次修改时间(返回时间戳) *

res = os.path.getmtime("123.py")

getatime() 获取文件最后一次访问时间(返回时间戳) *

res = os.path.getatime("123.py")
str_time = time.ctime(res)
print(str_time)

exists() 检测指定的路径是否存在 *

strvar = "/home/cuiwenjun/mywork/cuiwenjun11322132"
res = os.path.exists(strvar)
print(res)  # False

isabs() 检测一个路径是否是绝对路径 *

pathvar = "."
res = os.path.isabs(pathvar)
print(res)  # False

abspath() 将相对路径转换为绝对路径 *

pathnew = os.path.abspath(pathvar)
print(pathnew)  # /home/cuiwenjun/mywork
if not os.path.isabs(pathvar):
    pathnew = os.path.abspath(pathvar)
    print(pathnew)  # /home/cuiwenjun/mywork

四.计算文件夹大小

import os
pathvar = "/mnt/hgfs/python_gx/day19/ceshi100"

# # 基本写法
# lst = os.listdir(pathvar)
# print(lst)  # ['1.py', '2.py', '3.py', 'ceshi200']
#
# size = 0
# for i in lst:
#     # 拼接路径
#     pathnew = os.path.join(pathvar, i)
#     # 判断是否是文件
#     if os.path.isfile(pathnew):
#         print(i, "[文件]")
#         size += os.path.getsize(pathnew)
#
#     # 判断是否是文件夹
#     elif os.path.isdir(pathnew):
#         print(i, "[文件夹]")
#
# print(size)

"""不确定有多少层级的情况下,使用递归"""
def getallsize(pathvar):
    size = 0
    # 获取当前文件夹中所有内容
    lst = os.listdir(pathvar)
    # 循环列表
    for i in lst:
        # 拼接完整路径
        pathnew = os.path.join(pathvar, i)
        # 判断是否是文件或者文件夹
        if os.path.isfile(pathnew):
            size += os.path.getsize(pathnew)
        elif os.path.isdir(pathnew):
            # 如果是文件夹,继续调用函数
            size += getallsize(pathnew)
    # 返回最后的结果
    return size
res = getallsize(pathvar)
print(res)

五.tarfile 压缩模块 .tar | .tar.gz | .tar.bz2

import tarfile

1.创建tar包
“”“最小的压缩包,后缀格式为bz2"”"

# 单纯的tar包
with tarfile.open("ceshi0729_1.tar", "w", encoding="utf-8") as tf:
    tf.add("/bin/echo", "echo")
    tf.add("/bin/ed", "ed")
    tf.add("/bin/fuser", "tmp/fuser")
# .tsr.gz
with tarfile.open("ceshi0729_2.tar.gz", "w:gz", encoding="utf-8") as tf:
    tf.add("/bin/echo", "echo")
    tf.add("/bin/ed", "ed")
    tf.add("/bin/fuser", "tmp/fuser")
#  .tar.bz2
with tarfile.open("ceshi0729_3.tar.bz2", "w:bz2", encoding="utf-8") as tf:
    tf.add("/bin/echo", "echo")
    tf.add("/bin/ed", "ed")
    tf.add("/bin/fuser", "tmp/fuser")

2.对压缩包进行解压

with tarfile.open("ceshi0729_3.tar.bz2", "r", encoding="utf-8") as tf:
# 解压单个
    tf.extract("echo", "ceshi0729_4")
# 解压所有
    tf.extractall("ceshi0729_3")

3.追加文件(支持with语法)[只能为没有压缩过的tar包进行追加]

with tarfile.open("ceshi0729_1.tar", "a", encoding="utf-8") as tf:
    tf.add("/bin/cp", "cp")

4.查看压缩包中的文件

with tarfile.open("ceshi0729_2.tar.gz", "r", encoding="utf-8") as tf:
    lst = tf.getnames()
    print(lst)

如何处理tarfile不能在已经压缩过的包中追加内容的问题

# ceshi0729_3.tar.bz2
import os
path = os.getcwd()
# 找到要解压的包的路径
pathvar1 = os.path.join(path, "ceshi0729_3.tar.bz2")
print(pathvar1)
# 解压到哪里去
pathvar2 = os.path.join(path, "ceshi0729_3")
print(pathvar2)

# (1)先对已经压缩过的包进行解压
with tarfile.open(pathvar1, "r", encoding="utf-8") as tf:
    tf.extractall(pathvar2)

# (2)往这个解压的文件夹中添加新的文件
mybin = "cp -a /bin/fgrep " + pathvar2
# print(mybin)
os.system(mybin)

# (3)对这个文件进行过滤筛选,重新打包压缩(不要echo)
lst = os.listdir(pathvar2)
print(lst)
with tarfile.open(pathvar1, "w:bz2", encoding="utf-8") as tf:
    for i in lst:
        if i != "echo":
            # 拼接完整路径
            pathnew = os.path.join(pathvar2, i)
            # add(路径, 别名)
            tf.add(pathnew, i)

猜你喜欢

转载自blog.csdn.net/qq_45957580/article/details/107737044