0

I am searching for a file and its path in python, I get the result printed with the full path and file I am searching for. How do I set the print result as a variable so I can copy and move it to another folder?

import os

def find_files(filename, search_path):
    result = []

    for root, dir, files in os.walk(search_path):
        if filename in files:
            result.append(os.path.join(root, filename))
    return result 

print(find_files("myfile.exe","C:"))

When I run the .py file, it prints the full path of the file myfile.exe which is great, but how do I set it to get the path inside my function and move it to another folder/path?

I do not want to print the path of the file on the terminal, I want to use that path inside my program so I can use it to move it to another folder.

Thank you very much for your help!

constantstranger
  • 9,176
  • 2
  • 5
  • 19
IonutV
  • 31
  • 4

1 Answers1

1

If you extract the single item from result, you get path:

import os

def find_files(filename, search_path):
    result = []

    for root, dir, files in os.walk(search_path):
        if filename in files:
            result.append(os.path.join(root, filename))
    return result[0]

PATH = find_files("test", r"C:\Users\UserName\Desktop")
PATH

Output:

'C:\\Users\\UserName\\Desktop\\test'

Vovin
  • 720
  • 4
  • 16
  • Now if i want to move the file "test" to a different folder, when i do shutil.move(PATH, DESTINATION) with PATH and DESTINATION as variables i get the following exception in vs code, "rename: src should be a string, bytes or os.pathlike, not list". I will look into it now, any adivce is welcomed. – IonutV Apr 17 '22 at 19:42
  • @IonutV I guess that you did not extract a list in the function `return`. I could have answered clearer if you provide the code & output as the question update. – Vovin Apr 17 '22 at 19:46
  • i am sorry this was the code at the time, i just added the variables after your answer and did shutil.move. – IonutV Apr 17 '22 at 21:04