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__ 的使用方法)

沒有留言:

張貼留言

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...