What is the difference between os.path.basename() and os.path.dirname()?

后端 未结 2 1912
遥遥无期
遥遥无期 2021-01-29 18:49

What is the difference between os.path.basename() and os.path.dirname()?

I already searched for answers and read some links, but didn\'t unde

2条回答
  •  不思量自难忘°
    2021-01-29 19:20

    To summarize what was mentioned by Breno above

    Say you have a variable with a path to a file

    path = '/home/User/Desktop/myfile.py'
    

    os.path.basename(path) returns the string 'myfile.py'

    and

    os.path.dirname(path) returns the string '/home/User/Desktop' (without a trailing slash '/')

    These functions are used when you have to get the filename/directory name given a full path name.

    In case the file path is just the file name (e.g. instead of path = '/home/User/Desktop/myfile.py' you just have myfile.py), os.path.dirname(path) returns an empty string.

提交回复
热议问题