Python:遍历文件夹并选择第一个以 .txt 结尾的文件

Python: Iterate through a folder and pick first file that ends with .txt

我想遍历特定文件夹中的文件名。然后我希望选择满足条件的第一个文件名(文件名以'.txt'结尾)

当我看到第一个以 .txt 结尾的文件时,是否应该使用 For 循环并中断它? 还是应该使用 While 循环? While 循环似乎不起作用。它一直在继续。它继续按照以下代码打印文件名。

以下是我使用的代码:

import os
import pdb

asciipath = 'C:\Users\rmore\Desktop\Datalab'

x = 0

file = os.listdir(asciipath)

while file[x].endswith('.txt'):
    print(file[x])
    x = x+1

可以使用 while 循环执行此操作,但会使代码过于复杂。 我会在这里使用 for 循环。我还会将 file 重命名为 files 只是为了让正在发生的事情更加清楚。

编辑:

正如所指出的,循环的 else 子句将构成

files = os.listdir(asciipath)

for file in files:
    if file.endswith('.txt'):
        print(file)
        break
else:
    print('No txt file found')

找到第一个以 .txt 结尾的文件后,中断是停止循环的关键

另请注意,else 语句位于 for 循环中,而不是循环内部。只有当 break 语句没有被触发时,else 才会被触发。

Pythonic 方法是在生成器上使用 next

next((f for f in file if f.endswith('.txt')), 'file not found')

或者您可以遍历文件并 return 一旦条件匹配:

def find_first_txt_file(files)
    for file in files:
        if file.endswith('.txt'):
            return file
    return 'file not found'

使用 pathlib 和 glob 让自己更轻松。

from pathlib import Path
p = Path(asciipath)
print(next(p.glob('*.txt')))