Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

วิธีหาไฟล์ .txt ทั้งหมดในไดเรกทอรีด้วย Python

ใช้ os.listdir ดึงรายการทั้งหมด แล้วกรองเฉพาะไฟล์ที่ลงท้ายด้วย .txt

ตัวอย่าง

>>> import os
>>> file_list = [f for f in os.listdir('.') if os.path.isfile(os.path.join('.', f)) and f.endswith('.txt')]
>>> print(file_list)
['LICENSE.txt', 'NEWS.txt', 'README.txt']

เมธอด endswith ตรวจสอบว่า string ลงท้ายด้วย suffix ที่กำหนด

อีกวิธีใช้โมดูล glob:

>>> import glob, os
>>> file_list = [f for f in glob.glob("*.txt")]
>>> print(file_list)
['LICENSE.txt', 'NEWS.txt', 'README.txt']