I have a file, for example \"something.exe\" and I want to find path to this file
How can I do this in python?
Just to mention, another option to achieve this task could be the subprocess
module, to help us execute a command in terminal, like this:
import subprocess
command = "find"
directory = "/Possible/path/"
flag = "-iname"
file = "something.foo"
args = [command, directory, flag, file]
process = subprocess.run(args, stdout=subprocess.PIPE)
path = process.stdout.decode().strip("\n")
print(path)
With this we emulate passing the following command to the Terminal:
find /Posible/path -iname "something.foo"
.
After that, given that the attribute stdout
is binary string, we need to decode it, and remove the trailing "\n" character.
I tested it with the %timeit
magic in spyder, and the performance is 0.3 seconds slower than the os.walk()
option.
I noted that you are in Windows, so you may search for a command that behaves similar to find
in Unix.
Finally, if you have several files with the same name in different directories, the resulting string will contain all of them. In consequence, you need to deal with that appropriately, maybe using regular expressions.