用 glob 方式实现
from pathlib import Path
def get_file_paths(directory, include_extensions=None, exclude_extensions=None, exclude_temp_files=True):
"""
遍历指定目录下的所有文件,并返回它们的绝对路径。
可以指定要包括或排除的文件扩展名,并排除临时文件。
Args:
directory (str): 要遍历的目录路径。
include_extensions (list, optional): 要包括的文件扩展名列表。如果为 None,则不进行任何过滤。
exclude_extensions (list, optional): 要排除的文件扩展名列表。如果为 None,则不进行任何过滤。
exclude_temp_files (bool, optional): 是否排除临时文件。默认为 True。
Returns:
list: 包含所有符合条件文件绝对路径的列表。
"""
directory_path = Path(directory)
file_paths = []
for file_path in directory_path.glob('**/*'):
if file_path.is_file():
file_extension = file_path.suffix.lower()
# 检查是否满足include和exclude条件
if (include_extensions is None or file_extension in include_extensions) and \
(exclude_extensions is None or file_extension not in exclude_extensions) and \
(not exclude_temp_files or not file_path.name.startswith('~') and not file_path.name.endswith(
'.tmp')):
file_paths.append(str(file_path))
return file_paths
遍历指定目录下的所有文件,并返回它们的绝对路径。
可以指定要包括或排除的文件扩展名,并排除临时文件。
Args:
directory (str): 要遍历的目录路径。
include_extensions (list, optional): 要包括的文件扩展名列表。如果为 None,则不进行任何过滤。
exclude_extensions (list, optional): 要排除的文件扩展名列表。如果为 None,则不进行任何过滤。
exclude_temp_files (bool, optional): 是否排除临时文件。默认为 True。
Returns:
list: 包含所有符合条件文件绝对路径的列表。
import os
def get_file_paths(directory, include_extensions=None, exclude_extensions=None, exclude_temp_files=True):
"""
遍历指定目录下的所有文件,并返回它们的绝对路径。
可以指定要包括或排除的文件扩展名,并排除临时文件。
Args:
directory (str): 要遍历的目录路径。
include_extensions (list, optional): 要包括的文件扩展名列表。如果为 None,则不进行任何过滤。
exclude_extensions (list, optional): 要排除的文件扩展名列表。如果为 None,则不进行任何过滤。
exclude_temp_files (bool, optional): 是否排除临时文件。默认为 True。
Returns:
list: 包含所有符合条件文件绝对路径的列表。
"""
file_paths = []
for filename in os.listdir(directory):
file_path = os.path.join(directory, filename)
if os.path.isfile(file_path):
file_extension = os.path.splitext(filename)[1].lower()
# 检查是否满足include和exclude条件
if (include_extensions is None or file_extension in include_extensions) and \
(exclude_extensions is None or file_extension not in exclude_extensions) and \
(not exclude_temp_files or not filename.startswith('~') and not filename.endswith('.tmp')):
file_paths.append(file_path)
return file_paths
# 示例用法
directory_path = '/path/to/your/directory'
include_types = ['.xlsx', '.csv'] # 只包括 Excel 和 CSV 文件
exclude_types = ['.txt', '.log'] # 排除 TXT 和 LOG 文件
all_file_paths = get_file_paths(directory_path, include_extensions=include_types, exclude_extensions=exclude_types, exclude_temp_files=True)
for file_path in all_file_paths:
print(file_path)

2414

被折叠的 条评论
为什么被折叠?



