0

Let's assume that I have the following nested directories structure:

my_dir
|---- dir_1
|---- dir_2
|---- dir_3
      |---- dir_4
            |---- dir_5
                  |---- dir_6
                        |---- my_file.txt

How can I look if my_file.txt exists in any of the sub-directories of dir_3 (e.g. dir_4, dir_5, dir_6), and if exists how can I get its path? At the moment I tried with:

def file(name, path):
    for r, d, f in os.walk(abspath(path)):
        if name in files:
            return os.path.join(r, n)
    else:
         return 'file not found'

However, the above function is odd. How can I do the same with Pathlib?

anon
  • 836
  • 2
  • 9
  • 25

2 Answers2

1

delete your 'else' branch, so that you can continue walking the dir tree. then after the for loop, you can return 'file not found'.

lyh
  • 56
  • 4
1

Using Linux shell command

import os
cmd = 'find my_dir -name myfile.txt'
os.system(cmd)

This will search for myfile.txt in my_dir directory

or using subprocess module:

import subprocess
subprocess.Popen(["find","my_dir","-name","myfile.txt"])
Nagaraju
  • 1,853
  • 2
  • 27
  • 46