我想遍历特定文件夹中的文件名。然后,我希望选择第一个满足条件的文件名(文件名以“ .txt”结尾)
我应该使用For循环并在看到第一个以.txt结尾的文件时将其中断吗?还是应该使用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循环。我还将文件重命名为文件只是为了使发生的事情更加清楚。
正如所指出的,循环的else子句将使a
files = os.listdir(asciipath)
for file in files:
if file.endswith('.txt'):
print(file)
break
else:
print('No txt file found')
中断是找到第一个以.txt结尾的文件后停止循环的关键
还要注意,else语句在for循环上,而不是在循环内。 else只有在未触发break语句的情况下才会被触发。
一种Python方法是在生成器上使用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'
使您自己更轻松,并使用pathlib和glob。
from pathlib import Path
p = Path(asciipath)
print(next(p.glob('*.txt')))