How to loop over specific files in python.
Hi all,
Generally we wish to loop over specific category of files in python. So how do we do this.
Method 1 : -
Using glob
Method 2 :-
import glob, os os.chdir("/mydir") for file in glob.glob("*.txt"): print(file)
Without glob
import os
for file in os.listdir("/mydir"):
if file.endswith(".txt"):
print(file)
Method 3 :-Using Os.walk
import os
for root, dirs, files in os.walk("/mydir"):
for file in files:
if file.endswith(".txt"):
print(os.path.join(root, file))
Original source : - https://stackoverflow.com/questions/3964681/find-all-files-in-directory-with-extension-txt-in-python
Comments
Post a Comment