How can I find path to given file?

后端 未结 6 1328
伪装坚强ぢ
伪装坚强ぢ 2020-12-16 22:00

I have a file, for example \"something.exe\" and I want to find path to this file
How can I do this in python?

6条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-16 22:23

    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.

提交回复
热议问题