使用glob.glob()始终无法匹配到指定后缀文件该如何解决?
问题原因与修复方案
核心问题根源
glob.glob、pathlib.rglob默认不会自动解析路径中的~用户主目录占位符,你传入的路径会被识别为字面量以~开头的路径,无法匹配到真实路径,因此返回空列表。- 你已经通过
os.chdir('../repos/')切换到了仓库存储目录,使用全量绝对路径的写法冗余且容易出错,也可能因为相对路径跳转错误导致路径不匹配。
修复方案
方案1:展开用户主目录占位符
使用os.path.expanduser先处理路径中的~,再传给glob.glob:
# 先处理路径中的~ search_path = os.path.expanduser(r"~/Documents/open-vocabulary-ros/repos/**/*.cpp") target_files = glob.glob(search_path, recursive=True)
方案2:使用相对路径(更推荐)
已经切换到repos目录的前提下,直接用相对路径匹配,避免写全路径出错:
target_files = glob.glob("**/*.cpp", recursive=True)
方案3:pathlib rglob写法
如果使用pathlib,正确写法如下:
from pathlib import Path # 全路径写法 target_files = list(Path.home().joinpath("Documents/open-vocabulary-ros/repos").rglob("*.cpp")) # 相对路径写法(切换到repos目录后) target_files = list(Path.cwd().rglob("*.cpp"))
优化后的完整代码示例
import pandas as pd import os import subprocess import glob def get_repo_name_from_url(url): # 你原有实现保留即可 return url.strip().split('/')[-1].replace('.git', '') def download_cpp_files(csv_file): df = pd.read_csv(csv_file) df_url = df['URL'].tolist() # 建议这里用绝对路径切换目录,避免相对路径受脚本执行位置影响 # 比如 os.chdir(os.path.expanduser("~/Documents/open-vocabulary-ros/repos/")) os.chdir('../repos/') # 先打印当前工作目录确认跳转正确 print("当前工作目录:", os.getcwd()) for url in df_url: try: # 优化subprocess写法,避免shell注入风险 subprocess.call(['git', 'clone', url]) repo_name = get_repo_name_from_url(url) print(repo_name + " downloaded.") except Exception as e: print("No such URL " + url + " found.", e) # 仅扫描当前刚下载的仓库的cpp文件,效率更高 target_files = glob.glob(f"{repo_name}/**/*.cpp", recursive=True) print(target_files)
额外排查点
- 如果仍返回空,先确认下载的仓库中确实存在
.cpp后缀的文件,注意大小写,如果有大写.CPP后缀的文件,匹配规则调整为**/*.{cpp,CPP}即可。 - 确认
os.chdir跳转的路径正确,执行print(os.getcwd())打印当前工作目录,与实际仓库存储路径对比。
内容的提问来源于stack exchange,提问作者greendaysbomb
相关产品推荐
相关产品推荐

