Python 目录管理

来自CloudWiki
Cloud17讨论 | 贡献2020年3月29日 (日) 07:01的版本 显示目录内容
跳转至: 导航搜索

引入模块

import os

具体操作

查看当前目录

>>> os.getcwd()
'C:\\Users\\maxin\\AppData\\Local\\Programs\\Python\\Python37'
>>> 

创建目录

os.mkdir(os.getcwd()+'\\temp')

创建多级目录 ?os.makedirs(r“c:\python\test”)

切换目录

>>> os.chdir(os.getcwd()+'\\temp')

>>> os.getcwd()

'C:\\Users\\maxin\\AppData\\Local\\Programs\\Python\\Python37\\temp'

>>> os.chdir('..')

显示目录内容

>>> os.listdir('.')

['DLLs', 'Doc', 'include', 'Lib', 'libs', 'LICENSE.txt', 'NEWS.txt', 'python.exe', 'python3.dll', 'python37.dll', 'pythonw.exe', 'Scripts', 'tcl', 'temp', 'Tools', 'vcruntime140.dll']

>>> [fname for fname in os.listdir('.')if fname.endswith(('.exe', '.txt'))]

['LICENSE.txt', 'NEWS.txt', 'python.exe', 'pythonw.exe']

>>> for fname in os.listdir('.'):

if fname.endswith(('.exe', '.txt')):

print(fname)


LICENSE.txt
NEWS.txt
python.exe
pythonw.exe

删除目录

>>> os.listdir('.')

['DLLs', 'Doc', 'include', 'Lib', 'libs', 'LICENSE.txt', 'NEWS.txt', 'python.exe', 'python3.dll', 'python37.dll', 'pythonw.exe', 'Scripts', 'tcl', 'temp', 'Tools', 'vcruntime140.dll']

>>> os.rmdir('temp')

>>> os.listdir('.')

['DLLs', 'Doc', 'include', 'Lib', 'libs', 'LICENSE.txt', 'NEWS.txt', 'python.exe', 'python3.dll', 'python37.dll', 'pythonw.exe', 'Scripts', 'tcl', 'Tools', 'vcruntime140.dll']

查看目录空间占用情况

>>> os.path.getsize('pythonw.exe')

98320

>>> for fname in os.listdir('.'):

sub_path = os.path.join('.', fname)

if os.path.isfile(sub_path):

size =(os.path.getsize(sub_path))/1024 #换算成KB

print(fname,":",size,"KB")


LICENSE.txt : 29.48046875 KB
NEWS.txt : 703.82421875 KB
python.exe : 97.515625 KB
python3.dll : 57.515625 KB
python37.dll : 3663.015625 KB
pythonw.exe : 96.015625 KB
vcruntime140.dll : 87.6484375 KB

应用:统计目录占用空间

import os

totalSize = 0
fileNum = 0
dirNum = 0

def visitDir(path):
    global totalSize
    global fileNum
    global dirNum
    for lists in os.listdir(path):
        sub_path = os.path.join(path, lists)
        if os.path.isfile(sub_path):
            fileNum = fileNum+1                              #统计文件数量
            totalSize = totalSize+os.path.getsize(sub_path)  #统计文件总大小
        elif os.path.isdir(sub_path):
            dirNum = dirNum+1                                #统计文件夹数量
            visitDir(sub_path)                               #递归遍历子文件夹

def main(path):
    if not os.path.isdir(path):
        print('Error:"', path, '" is not a directory or does not exist.')
        return
    visitDir(path)

def sizeConvert(size):                                   #单位换算
    K, M, G = 1024, 1024**2, 1024**3
    if size >= G:
        return str(size/G)+'G Bytes'
    elif size >= M:
        return str(size/M)+'M Bytes'
    elif size >= K:
        return str(size/K)+'K Bytes'
    else:
        return str(size)+'Bytes'

def output(path):
    print('The total size of '+path+' is:'+sizeConvert(totalSize)
          +'('+str(totalSize)+' Bytes)')
    print('The total number of files in '+path+' is:',fileNum)
    print('The total number of directories in '+path+' is:',dirNum)

if __name__=='__main__':
    path = r'D:\teaching\自动化运维'
    main(path)
    output(path)

应用:复制空目录

云盘备份:有的时候需要将云端的目录结构复制到本地