当我看到第一个以.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
方便自己使用 pathlib 还有地球。
from pathlib import Path p = Path(asciipath) print(next(p.glob('*.txt')))
一种蟒蛇式的方法是 next
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'
使用while循环可以做到这一点,但这会使代码过于复杂。
如前所述,循环的else子句将使
files = os.listdir(asciipath) for file in files: if file.endswith('.txt'): print(file) break else: print('No txt file found')
在找到以.txt结尾的第一个文件后,中断是停止循环的关键