Python筛选目录下的文件

本文介绍如何使用Python的glob、re和fnmatch模块来过滤特定目录下的文件,包括基本的文件扩展名过滤和复杂的正则表达式匹配。通过实例演示了如何筛选jpg、jpeg等图片文件,以及如何使用list comprehension和正则表达式进行更复杂的需求匹配。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

From: https://stackoverflow.com/questions/2225564/get-a-filtered-list-of-files-in-a-directory

Method one:

glob.glob('145592*.jpg')

glob.glob() is definitely the way to do it (as per Ignacio). However, if you do need more complicated matching, you can do it with a list comprehension and re.match(), something like so:

files = [f for f in os.listdir('.') if re.match(r'[0-9]+.*\.jpg', f)]

Keep it simple:

import os
relevant_path = "[path to folder]"
included_extensions = ['jpg','jpeg', 'bmp', 'png', 'gif']
file_names = [fn for fn in os.listdir(relevant_path)
              if any(fn.endswith(ext) for ext in included_extensions)]

Another option:

>>> import os, fnmatch
>>> fnmatch.filter(os.listdir('.'), '*.py')
['manage.py']

https://docs.python.org/3/library/fnmatch.html

 

 

### 使用Python根据条件筛选文件Python中可以根据多种条件来筛选文件,这通常涉及到遍历目录中的文件并应用特定逻辑判断哪些文件应被选中。下面介绍几种常见的方式。 #### 基于文件名模式匹配筛选文件 当目标是从大量文件里挑选出名称符合一定规律的那些时,可以利用`os.listdir()`函数获取指定路径下的所有文件名列表,并通过字符串操作或正则表达式来进行过滤[^2]: ```python import re import os def select_files_by_pattern(directory, pattern): selected_files = [] for filename in os.listdir(directory): if re.match(pattern, filename): full_path = os.path.join(directory, filename) selected_files.append(full_path) return selected_files ``` 此方法适用于已知确切命名规则的情况;如果只是简单比较部分字符相同,则可以直接使用`str.startswith()`, `str.endswith()` 或者直接用等于号(`==`)做对比[^3]。 #### 根据Excel表格内的字段值筛选对应文件 有时需要依据外部数据源(比如Excel表)里的记录去定位相应的文件。此时可先读取Excel文档得到所需的信息列,再循环检查每个文件是否符合条件后再决定复制与否: ```python import pandas as pd import shutil df = pd.read_excel('./data.xlsx') for file_name in os.listdir(source_dir): fid_part = file_name.split('_')[index_of_fid_in_filename] if any(str(fid) == fid_part for fid in df['FID']): src_file = os.path.join(source_dir, file_name) dst_file = os.path.join(destination_dir, file_name) shutil.copy(src_file, dst_file) print("Selection completed.") ``` 这段代码展示了如何基于DataFrame对象内部的数据项与待处理文件之间的关联关系完成精准的选择工作。 #### 批量处理CSV文件内容作为筛选标准 对于存储结构化数据的CSV文件而言,可以通过Pandas库加载这些资源并对其中的内容执行查询语句从而达到目的[^4]: ```python import glob import pandas as pd all_csvs = glob.glob(path_to_folder + "*.csv") selected_dataframes = [] for csv_file in all_csvs: temp_df = pd.read_csv(csv_file) filtered_rows = temp_df[temp_df['column_name'].isin(target_values)] if not filtered_rows.empty: selected_dataframes.append(filtered_rows) final_result = pd.concat(selected_dataframes).reset_index(drop=True) ``` 这里实现了对多个CSV文件内特定列值属于给定集合的所有行进行提取的功能。 #### XML文件节点属性或文本内容为基础的筛选 针对XML类型的配置或其他形式描述性的文件,借助ElementTree模块解析其树状结构之后便能方便地访问各个标签及其子元素,进而实施更复杂的检索策略[^5]: ```python from xml.etree import ElementTree as ET tree = ET.parse(xml_file_path) root = tree.getroot() interesting_elements = root.findall(".//element[@attribute='value']") # Or search by text content within elements text_matches = [elem.text for elem in root.iter(tag="some_tag") if "target string" in (elem.text or '')] if interesting_elements or text_matches: # Do something with the found items... ``` 上述例子说明了怎样按照XML文档中定义好的标记特征选取感兴趣的片段。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值