引入os文件来读取文件夹,遍历所有文件:
import os
遍历文件夹中所有文件:
for root, dirs, files in os.walk(path):
for file in files:
file_path = os.path.join(root, file)
判断指定后缀名文件,并统计数量,输出结果:
if os.path.splitext(file)[1] == ext:
#print(file_path)
NUM_COUNT = NUM_COUNT+1
print('+1',NUM_COUNT,file_path)
运行结果:
完整代码:
import os
# 输出文件中所有某种后缀名文件的数量
path = input('请输入路径')
ext = input('请输入要统计的文件后缀')
NUM_COUNT = 0
def selfile(path,ext):
global NUM_COUNT
for root, dirs, files in os.walk(path):
for file in files:
file_path = os.path.join(root, file)
if os.path.splitext(file)[1] == ext:
#print(file_path)
NUM_COUNT = NUM_COUNT+1
print('+1',NUM_COUNT,file_path)
selfile(path,ext)