在 Python 中查找扩展名为 .txt 的目录中的所有文件 [英] Find all files in a directory with extension .txt in Python

查看:26
本文介绍了在 Python 中查找扩展名为 .txt 的目录中的所有文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在python中找到扩展名为.txt的目录中的所有文件?

How can I find all the files in a directory having the extension .txt in python?

推荐答案

您可以使用 <代码>glob:

You can use glob:

import glob, os
os.chdir("/mydir")
for file in glob.glob("*.txt"):
    print(file)

或者简单地os.listdir:

or simply os.listdir:

import os
for file in os.listdir("/mydir"):
    if file.endswith(".txt"):
        print(os.path.join("/mydir", file))

或者如果你想遍历目录,使用 os.步行:

or if you want to traverse directory, use os.walk:

import os
for root, dirs, files in os.walk("/mydir"):
    for file in files:
        if file.endswith(".txt"):
             print(os.path.join(root, file))

这篇关于在 Python 中查找扩展名为 .txt 的目录中的所有文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆