2019-05-23:目录操作练习

#encoding=utf-8
"""
统计某个目录下文件数和目录个数
"""

import os
dirNum=0
fileNum=0
for file_or_dirs in os.listdir("e:\\murphy"):
    os.chdir("e:\\murphy")
    if os.path.isfile(file_or_dirs):
        fileNum+=1
    if os.path.isdir("e:\\murphy"):
        dirNum+=1
print("目录树",dirNum)
print("文件数量",fileNum)

"""
删除某个目录下的全部文件(仅限一级目录)
"""
def removeAllfiles(path):
    for file_or_dirs in os.listdir(path):
        os.chdir(path)
        if os.path.isfile(file_or_dirs):
            os.remove(file_or_dirs)

print(removeAllfiles("e:\\murphy\\test"))

"""
使用程序建立一个多级的目录,在每个目录下,新建一个和目录名字一样的txt文件
"""
def createDirsAndFiles(path):
    os.chdir(path)
    for i in range(4):
        os.mkdir(str(i))
        os.chdir(str(i))
        with open(str(i)+".txt","w",encoding="utf8") as fp:
            pass
print(createDirsAndFiles("e:\\murphy\\test"))

猜你喜欢

转载自blog.csdn.net/sinat_18722099/article/details/90437013
今日推荐