How can I find path to given file?

后端 未结 6 1335
伪装坚强ぢ
伪装坚强ぢ 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:37

    use os.path.abspath to get a normalized absolutized version of the pathname
    use os.walk to get it's location

    import os
    exe = 'something.exe'
    #if the exe just in current dir
    print os.path.abspath(exe)
    # output
    # D:\python\note\something.exe
    
    #if we need find it first
    for root, dirs, files in os.walk(r'D:\python'):
        for name in files:
            if name == exe:
                print os.path.abspath(os.path.join(root, name))
    
    # output
    # D:\python\note\something.exe
    

提交回复
热议问题