2013-06-29 42 views
0

我想在腳本中接受一個參數,就像「mkdir」一樣。如果參數只是一個名稱,即helloworld,它將使用[pwd]/helloworld。如果它包含可以作爲文件路徑的東西,即../helloworld,/home/x/helloworld, ~/helloworld等,則它將使用這些來解析最終路徑。有這樣的圖書館嗎? Python甚至能夠獲得創建它的shell的工作目錄嗎?從Python的shell工作目錄獲取文件路徑?

編輯:沒關係愚蠢的賞金,不知道是什麼原因導致了問題,但它現在工作正常。

回答

3

我認爲這是你在找什麼:

import os 
os.path.realpath(__file__) 
0

我覺得你有興趣os.getcwd()功能。它返回一個代表當前工作目錄

>>> import os 
>>> os.getcwd() 
'/home/user/work' 

一個字符串或者一個可以使用os.getcwdu()用於獲取Unicode的結果。它返回一個表示當前工作目錄的unicode字符串。

>>> import os 
>>> os.getcwdu() 
u'/home/user/work' 
+0

但這只是問題的一小部分。原來我想'os.path.realpath',只是它不能解析'〜/' – tkbx

1

os.path.expanduser(path)將擴大〜和〜用戶對用戶的主目錄(http://docs.python.org/2/library/os.path.html)。

os.getcwd()將爲您提供當前(目前)的工作目錄。

os.path.realpath(__file__)將返回Python腳本所在的目錄。

2

做到這一點的方法如下:

os.path.realpath(os.path.expanduser(__file__)) 

默認情況下,真實路徑()不處理tildas,所以你需要expanduser()做骯髒的工作。

0

您可能想考慮使用Unipath。對路徑計算的許多輔助功能以及字符串的路徑計算(子類海峽或Unicode)

原來這是一個在Unix上:https://github.com/mikeorr/Unipath

在Windows上一個工作太(我做了一些修正,以它):https://github.com/sesas/Unipath

>>> import unipath 
>>> p = unipath.Path() 
>>> p 
Path(u'.') 
>>> p.absolute() 
Path(u'C:\\Python27\\Lib\\idlelib') 
>>> p.child('hello_world') 
Path(u'.\\hello_world') 
>>> p = unipath.Path(__file__) # cannot actually do this in IDLE 
>>> dir(p) 
['__add__', '__class__', '__contains__', '__delattr__', '__dict__', '__doc__', 
'__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', 
'__getslice__', '__gt__', '__hash__', '__init__', '__le__', '__len__', '__lt__', '__mod__', 
'__module__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', 
'__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 
'__weakref__', '_formatter_field_name_split', '_formatter_parser', '_new_helper', '_walk', 
'absolute', 'ancestor', 'atime', 'auto_norm', 'capitalize', 'center', 'chdir', 'child', 
'chmod', 'components', 'copy', 'copy_stat', 'copy_tree', 'count', 'ctime', 'cwd', 'decode', 
'encode', 'endswith', 'exists', 'expand', 'expand_user', 'expand_vars', 'expandtabs', 
'ext', 'find', 'format', 'index', 'isabsolute', 'isalnum', 'isalpha', 'isdecimal', 
'isdigit', 'isdir', 'isfile', 'islink', 'islower', 'ismount', 'isnumeric', 'isspace', 
'istitle', 'isupper', 'join', 'lexists', 'listdir', 'ljust', 'lower', 'lstat', 'lstrip', 
'mkdir', 'move', 'mtime', 'name', 'needs_update', 'norm', 'norm_case', 'parent', 
'partition', 'pathlib', 'read_file', 'rel_path_to', 'relative', 'remove', 'rename', 
'replace', 'resolve', 'rfind', 'rindex', 'rjust', 'rmdir', 'rmtree', 'rpartition', 
'rsplit', 'rstrip', 'set_times', 'size', 'split', 'split_root', 'splitlines', 'startswith', 
'stat', 'stem', 'strip', 'swapcase', 'title', 'translate', 'upper', 'walk', 'write_file', 
'zfill']