0

I have a file named 'my_file.txt'. How can I get the exact paths of the file existence in Python?

Expected output as a list, ['C:/sample_folder/my_file.txt', 'C:/another_folder/test_folder/my_file.txt']

Sohn
  • 168
  • 3
  • 12

1 Answers1

1

You can use os.walk.

import os
for root, dirs, files in os.walk('/'):
    for name in files:
        if name == 'README.md':
            path = os.path.join(root, name)
            print(path)

There's also glob:

import glob
for path in glob.iglob('/**/README.md', recursive=True):
    print(path)

And there's also pathlib, an object-oriented interface to many existing functions:

from pathlib import Path
for path in Path('C:/').glob('**/*.txt'):
    print(path)
Josh Lee
  • 161,055
  • 37
  • 262
  • 269