1 目录结构
D:\DOWNLOADS
│ 示例.doc
│
├─Excel
│ 表格1.xlsx
│ 表格2.xlsx
│
└─World
文档1.doc
文档2.doc
2 获取目录下文件列表
# -*- coding: UTF-8 -*-
import os
def get_filenames_list(folder_path):
file_list = []
for root, dirs, files in os.walk(folder_path):
for file in files:
file_list.append(os.path.join(root,file))
return file_list
if __name__ == '__main__':
folder = "D:\\Downloads"
file_list = get_filenames_list(folder)
print(file_list)
'''
输出:
['D:\\Downloads\\1.txt',
'D:\\Downloads\\示例.doc',
'D:\\Downloads\\Excel\\表格1.xlsx',
'D:\\Downloads\\Excel\\表格2.xlsx',
'D:\\Downloads\\World\\文档1.doc',
'D:\\Downloads\\World\\文档2.doc']
'''
3 获取特定扩展名文件数量
# -*- coding: UTF-8 -*-
import os
def count_files_with_extension(folder_path, extension):
count = 0
for root, dirs, files in os.walk(folder_path):
for file in files:
if file.endswith(extension):
count += 1
return count
if __name__ == '__main__':
folder = "D:\\Downloads"
extension = ".doc"
file_count = count_files_with_extension(folder, extension)
print(f"The number of {extension} files in {folder} is {file_count}.")
'''
输出:
The number of .doc files in D:\Downloads is 3.
'''
4 其他
folder = "D:\\Downloads"
for root, dirs, files in os.walk(folder):
'''
# 遍历目录下所有目录
for dir in dirs:
# 获取目录名称
print(dir)
# 获取目录路径
print(os.path.join(root, dir))
'''
'''
输出:
Excel
D:\Downloads\Excel
World
D:\Downloads\World
'''
# 遍历目录下所有文件
for file in files:
# 获取文件所属目录
# print(root)
# 获取文件名
# print(file)
# 获取文件名-全路径
print(os.path.join(root,file))
'''
输出:
D:\Downloads
示例.doc
D:\Downloads\示例.doc
D:\Downloads\Excel
表格1.xlsx
D:\Downloads\Excel\表格1.xlsx
D:\Downloads\Excel
表格2.xlsx
D:\Downloads\Excel\表格2.xlsx
D:\Downloads\World
文档1.doc
D:\Downloads\World\文档1.doc
D:\Downloads\World
文档2.doc
D:\Downloads\World\文档2.doc
'''
参考:
Python 统计具有特定扩展名的文件数量
https://deepinout.com/python/python-qa/505_python_count_number_of_files_with_certain_extension_in_python.html
windows cmd 生成文件目录树
https://www.cnblogs.com/wkfvawl/p/11944501.html