I want to exclude the directory 'dir3_txt' so that I can only capture the files('.txt') from other directory . I tried to exclude directory like below but not able to figure it out how to get all the files having .txt as ext other that having it in dir3_txt using below:
for root, dirs, files in os.walk('.'):
print (root)
dirs[:] = [d for d in dirs if not d.startswith('dir3')]
for file in files:
print (os.path.join(root, file))
I am thinking of glob (got below from stack itself) but not sure how to tweak glob to use it.
for file in os.walk('.'):
for txt in glob(os.path.join(files[0], '*.txt')):
print(txt)
I went through Excluding directories in os.walk but the solution provided is not helping me, also it only tells about skipping directory that also is not helpful as I need to get files from other directories , better if we can do it with glob only?
A simple solution would just to do a string comparison against the directory-paths and files returned by os.walk:
for root, dirs, files in os.walk('.'):
if "/dir3_txt/" not in root:
for file in files:
if file.endswith(".txt"):
print (os.path.join(root, file))
for root, dirs, files in os.walk('.'):
print (root)
dirs[:]= [d for d in dirs if d[:4]!='dir3']
for file in files:
if file[-4:]=='.txt':
print (os.path.join(root, file))
I dont have any system with me now to test this , so if any problems please comment.
Edit:
Now it only detects '.txt' files.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With