Py学习  »  Python

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

rmore911 • 5 年前 • 1985 次点击  

当我看到第一个以.txt结尾的文件时,应该使用For循环并中断它吗? 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
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/56597
文章 [ 3 ]  |  最新文章 5 年前
David Nehme
Reply   •   1 楼
David Nehme    5 年前

方便自己使用 pathlib 还有地球。

from pathlib import Path
p = Path(asciipath)
print(next(p.glob('*.txt')))
Austin
Reply   •   2 楼
Austin    5 年前

一种蟒蛇式的方法是 next

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

或者,您可以循环文件并在条件匹配时立即返回:

def find_first_txt_file(files)
    for file in files:
        if file.endswith('.txt'):
            return file
    return 'file not found'
Rashid 'Lee' Ibrahim
Reply   •   3 楼
Rashid 'Lee' Ibrahim    5 年前

使用while循环可以做到这一点,但这会使代码过于复杂。

编辑:

如前所述,循环的else子句将使

files = os.listdir(asciipath)

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

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