How do I get the full path of the current file's directory?

前端 未结 15 1153
傲寒
傲寒 2020-11-22 17:01

I want to get the current file\'s directory path. I tried:

>>> os.path.abspath(__file__)
\'C:\\\\python27\\\\test.py\'

But how can

15条回答
  •  甜味超标
    2020-11-22 17:22

    I found the following commands will all return the full path of the parent directory of a Python 3.6 script.

    Python 3.6 Script:

    #!/usr/bin/env python3.6
    # -*- coding: utf-8 -*-
    
    from pathlib import Path
    
    #Get the absolute path of a Python3.6 script
    dir1 = Path().resolve()  #Make the path absolute, resolving any symlinks.
    dir2 = Path().absolute() #See @RonKalian answer 
    dir3 = Path(__file__).parent.absolute() #See @Arminius answer 
    
    print(f'dir1={dir1}\ndir2={dir2}\ndir3={dir3}')
    

    Explanation links: .resolve(), .absolute(), Path(file).parent().absolute()

提交回复
热议问题