0

is there any way to find file path not in same dir of project by file name only

I don't want to save file to project dir and use it .

Khalid
  • 1
  • 1

1 Answers1

0

You can use the os module, which provides several functions for interacting with the file system.

import os

filename = "my_file.txt"
# Search in <search_path>
search_path = "C:/Users/MyUserName/Documents"

for root, dirs, files in os.walk(search_path):
    if filename in files:
        file_path = os.path.join(root, filename)
        print(f"The path of {filename} is {file_path}")

The os.walk() function traverse the directory tree rooted at search_path.

If we find the file, we can use the os.path.join() function to concatenate the directory path with the file name, giving us the full path to the file.

Yuri
  • 256
  • 3
  • 7