python基础_os模块

1.os模块 

# ### os模块 -对系统进行操作
import os
#system()  在python中执行系统命令
# os.system("mkdir ceshi0822") # linux
# os.system("mspaint")         # windows
# os.system("ipconfig")

#popen()   执行系统命令返回对象,通过read方法读出字符串
obj = os.popen("ifconfig")
print(obj)
# 通过read方法直接把转换为utf-8的字符串读取出来
print(obj.read())

#listdir() 获取指定文件夹中所有内容的名称列表
# 路径:相对路径,绝对路径  .代表相对于当前

# 相对
# lst = os.listdir(".")
# 绝对
lst = os.listdir("/home/wangwen/")
print(lst)
"""
['1.py', '2.py', '20190822_1.json_pickle.mp4', '20190822_2.random.mp4', '20190822_3.time.mp4', '3.py', '4.py', 'ceshi1.json', 'ceshi2.json', 'ceshi3.pkl', 'part10.md', 'part11.md']
"""

#getcwd()  获取当前文件所在的默认路径
# 完整的目录
res = os.getcwd()
print(res) # /mnt/hgfs/gongxiang16/day15
# 完整的目录 + 文件名
print(__file__)

#chdir()   修改当前文件工作的默认路径
os.chdir("/home/wangwen/")
# os.system("touch 1.txt11")
os.system("rm -rf 1.txt11")

 2.os.path模块

strvar = os.path.join(path1,path2,path3)
print(strvar)  #路径拼接
res = os.path.basename(pathvar)
res = os.path.dirname(pathvar)
res = os.path.split(pathvar)
res = os.path.splitext(pathvar)
res = os.path.getsize("1.txt")
res = os.path.isdir("1.py")
res = os.path.isfile("1.txt")    
res = os.path.islink("./ceshi002/ceshi001")
res = os.path.getctime("1.txt")
res = os.path.exists(pathvar)
res = os.path.abspath(path123)

3.递归法计算文件夹的大小

# (2) 递归计算文件夹大小
pathvar = "/mnt/hgfs/gongxiang16/day16/ceshi100"
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):
            # "/mnt/hgfs/gongxiang16/day16/ceshi100/ceshi200"
            print(i,"文件夹")
            size += getallsize(pathnew)
    return size
    
res = getallsize(pathvar)
print(res)
原文地址:https://www.cnblogs.com/jalen-123/p/13173810.html