Python 如何列出目录的oly txt文件?
如何列出目录的oly txt文件?。。。 如何筛选到txt文件Python 如何列出目录的oly txt文件?,python,tkinter,Python,Tkinter,如何列出目录的oly txt文件?。。。 如何筛选到txt文件 从操作系统导入listdir 从os.path导入isfile,加入 onlyfiles=[f表示listdir中的f(“D:\hacking\python”),如果是isfile( 加入(“D:\hacking\python”,f))] 打印(仅限文件) 您可以在列表中添加和条件,以检查文件扩展名,如下所示: from os import listdir from os.path import isfile, join onlyf
从操作系统导入listdir
从os.path导入isfile,加入
onlyfiles=[f表示listdir中的f(“D:\hacking\python”),如果是isfile(
加入(“D:\hacking\python”,f))]
打印(仅限文件)
您可以在列表中添加和
条件,以检查文件扩展名,如下所示:
from os import listdir
from os.path import isfile, join
onlyfiles = [f for f in listdir("D:\hacking\python") if isfile(
join("D:\hacking\python", f)) and f.endswith(".txt")]
print(onlyfiles)
.endswith()
函数非常简单;它检查字符串是否以给定的子字符串结尾。您可以从模块glob
使用函数glob
,该函数支持通配符并返回完整路径名。如果您确定所有以.txt
结尾的路径始终是常规文件(或者如果您不在乎,只希望所有路径都以.txt
结尾,而不管它是什么类型的路径),那么代码就是:
import glob
onlyfiles = glob.glob(r"D:\hacking\python\*.txt")
否则:
import glob
from os.path import isfile
onlyfiles = [x for x in glob.iglob(r"D:\hacking\python\*.txt") if isfile(x)]
注意:iglob
返回迭代器而不是列表,因此在这种情况下使用更有效
如果不需要完整的路径名:
import glob
from os.path import isfile, split
onlyfiles = [split(x)[-1] for x in glob.iglob(r"D:\hacking\python\*.txt") if isfile(x)]
只需在列表中添加“and f.endswith(“.txt”)”,这是否回答了您的问题?