2017年8月24日 星期四

[ Python 常見問題 ] Find current directory and file's directory

Source From Here 
Question 
In Python, what commands can I use to find: 
1. the current directory (where I was in the terminal when I ran the Python script), and
2. where the file I am executing is?

How-To 
To get the full path to the directory a Python file is contained in, write this in that file: 
  1. import os   
  2. dir_path = os.path.dirname(os.path.realpath(__file__))  
(Note that the incantation above won't work if you've already used os.chdir() to change your current working directory, since the value of the __file__ constant is relative to the current working directory and is not changed by an os.chdir()call.) To get the current working directory use 
  1. import os  
  2. cwd = os.getcwd()  
Documentation references for the modules, constants and functions used above: 
* The os and os.path modules.
* The __file__ constant
* os.path.realpath(path) (returns "the canonical path of the specified filename, eliminating any symbolic links encountered in the path")
* os.path.dirname(path) (returns "the directory name of pathname path")
* os.getcwd() (returns "a string representing the current working directory")
* os.chdir(path) ("change the current working directory to path")


Supplement 
Python 獲取文件路徑及文件目錄(__file__ 的使用方法)

沒有留言:

張貼留言

[ Python 文章收集 ] SQLAlchemy quick start with PostgreSQL

Source From   Here   Preface   This is a quick tutorial for getting started with   SQLAlchemy Core API .   Prerequisites   In this quick st...