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

ฉันจะวนซ้ำไฟล์ในไดเรกทอรีที่กำหนดใน Python ได้อย่างไร


os.listdir(my_path) จะช่วยให้คุณได้รับทุกสิ่งที่อยู่ในไดเรกทอรี my_path - ไฟล์และไดเร็กทอรี คุณสามารถใช้ได้ดังนี้:

>>> import os
>>> os.listdir('.')
['DLLs', 'Doc', 'etc', 'include', 'Lib', 'libs', 'LICENSE.txt', 'NEWS.txt', 'python.exe', 'pythonw.exe', 'README.txt', 'Scripts', 'share', 'tcl', 'Tools', 'w9xpopen.exe']

หากคุณต้องการเพียงแค่ไฟล์ คุณสามารถกรองโดยใช้ isfile:

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