跳到主要内容

Python 程序:查找目录内所有带 .txt 扩展名的文件

要理解此示例,您应该具备以下Python编程主题的知识:

示例 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 扩展名。