os及os.path练习题

查找目录下每个文件的数量(考察获取文件后缀名以及获取当前目录下文件方法)

import os

#获取目录下的所有文件
list = os.listdir('.')
filetype = {} 
for f in list:
    print("文件名:",f)
    temp = os.path.splitext(f)
    print("后缀:",temp)
    isbool = temp[1] in filetype.keys()
    if isbool:
        num = filetype[temp[1]]
        filetype[temp[1]] = int(num)+1
    else:
        filetype[temp[1]]=1
print(filetype)

获取当前目录下所有文件的大小总和

'''
当前文件夹下所有文件大小总和
'''
import os

#获取当前文件夹下所有的文件
list = os.listdir('.')

total = 0 #文件总大小
#遍历所有文件并获取大小
for f in list:
    size = os.path.getsize(f)
    print("文件%s的大小%f",f,size)
    total = total + size
print('总共文件大小为:',total)
原文地址:https://www.cnblogs.com/pengpengzhang/p/8677082.html