示例 1:使用 glob
import glob, os
os.chdir("my_dir")
for file in glob.glob("*.txt"):
print(file)
输出
c.txt b.txt a.txt
使用 glob
模块,您可以搜索具有特定扩展名的文件。
os.chdir("my_dir")
将当前工作目录设置为/my_dir
。- 使用 for 循环,您可以使用
glob()
搜索具有.txt
扩展名的文件。 *
表示所有具有给定扩展名的文件。
示例 2:使用 os
import os
for file in os.listdir("my_dir"):
if file.endswith(".txt"):
print(file)
输出
a.txt b.txt c.txt
在此示例中,我们使用 endswith() 方法检查 .txt
扩展名。
- 使用 for 循环,遍历目录
/my_dir
中的每个文件。 - 使用
endswith()
检查文件是否具有.txt
扩展名。
使用 os.walk
import os
for root, dirs, files in os.walk("my_dir"):
for file in files:
if file.endswith(".txt"):
print(file)
输出
c.txt b.txt a.txt
此示例使用 os
模块的 walk()
方法。
- 使用 for 循环,遍历
my_dir
中的每个files
。 - 使用
endswith()
检查文件是否具有.txt
扩展名。
另请阅读