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
  • 166
  • 3
  • 13

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
  • 171,072
  • 38
  • 269
  • 275