简体   繁体   中英

How to get filepath in Python using the filename?

I know the name of the file stored on my pc which I want to open in a web page application. I need the to send the filepath to a html file for the same. So I want to get filepath using the filename in Python or HTML.

I tried using the os.path.dirname(filename) in Python but it didn't work because the attribute is supposed to be a path for this function.

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

code :

import os
file_ = 'filename.txt'

for root, dirs, files in os.walk('C:/'):
    for name in files:
        if file_ in name:
            print (os.path.abspath(os.path.join(root, name)))

output:

C:\Users\User\Desktop\filename.txt

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM