如何用Python判断/etc/NetworkManager目录下是否存在*.nmconnection文件?
解决方法:判断指定目录下是否存在特定后缀文件
你可以直接通过文件匹配来判断/etc/NetworkManager/system-connections/目录下是否存在*.nmconnection文件,不用切换工作目录,下面提供两种简洁的实现方式:
方式一:使用glob库(兼容所有Python版本)
import glob def has_nmconnection_files(): # 直接匹配目标路径下的所有*.nmconnection文件 matched_files = glob.glob("/etc/NetworkManager/system-connections/*.nmconnection") # 匹配结果不为空则返回True,否则返回False return len(matched_files) > 0 # 调用示例 print(has_nmconnection_files())
方式二:使用pathlib库(Python3.4+推荐)
pathlib是更现代的路径操作库,代码可读性和效率更高:
from pathlib import Path def has_nmconnection_files(): target_dir = Path("/etc/NetworkManager/system-connections") # 先判断目标目录是否存在,避免目录不存在时的异常 if not target_dir.is_dir(): return False # 只要找到一个后缀为.nmconnection的文件就返回True,无需遍历全部 return any(file.suffix == ".nmconnection" for file in target_dir.iterdir()) # 调用示例 print(has_nmconnection_files())
补充说明
你之前用os.path.isdir只能判断目录是否存在,无法直接检测目录内的特定文件,所以需要结合文件匹配逻辑来实现需求。另外,避免使用os.chdir切换工作目录,防止影响后续代码的路径处理逻辑。
内容的提问来源于stack exchange,提问作者user21379959
相关产品推荐
相关产品推荐

