You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python如何统计目录下无扩展名的文件并获取其basename

方案1:基于原有os+glob逻辑修改

直接调整匹配规则+过滤逻辑即可,这种方式兼容性最好,也方便处理边界场景:

import os
import glob

# 先读取目标目录下所有文件
all_files = glob.glob(os.path.join(UserInput[0], '*'))
# 筛选无扩展名的文件:判断文件名不含后缀点,且是文件(排除目录)
names = [
    os.path.basename(x) 
    for x in all_files 
    if os.path.isfile(x) and '.' not in os.path.basename(x)
]

# 输出逻辑和原代码一致
for i in names:
    print("file found - "+i)

如果需要把.gitignore这类开头带点的隐藏文件也判定为无扩展名文件,修改过滤条件即可:

names = [
    os.path.basename(x) 
    for x in all_files 
    if os.path.isfile(x) and '.' not in os.path.basename(x).lstrip('.')
]

方案2:用pathlib实现(Python3.4+支持,代码更简洁)

pathlib内置的suffix属性可以直接读取文件扩展名,判断为空即可筛选无扩展名文件:

from pathlib import Path

target_dir = Path(UserInput[0])
names = [
    f.name 
    for f in target_dir.iterdir() 
    # 若要排除隐藏文件,可追加条件 and not f.name.startswith('.')
    if f.is_file() and f.suffix == ''
]

for i in names:
    print("file found - "+i)

内容的提问来源于stack exchange,提问作者1barrowvian1

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 12:27:02