Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ignore files from specific directory using glob or by os.walk()

Tags:

python

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?

like image 724
steveJ Avatar asked Dec 07 '25 10:12

steveJ


2 Answers

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))
like image 186
maxymoo Avatar answered Dec 10 '25 01:12

maxymoo


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.

like image 40
Yashik Avatar answered Dec 10 '25 00:12

Yashik