2010-04-29 91 views
59

如何在尾部斜槓尚未存在的情況下將尾部斜槓(* nix的/,win32的\)添加到目錄字符串中?謝謝!Python,將尾部斜槓添加到目錄字符串,獨立操作系統

+0

你想用它做什麼? – 2010-04-29 09:31:03

+5

您應該使用'os.path'模塊(http://docs.python.org/library/os.path.html)而不是直接操作字符串。使用'os.path.join'連接路徑組件。 – kennytm 2010-04-29 09:33:56

+0

@Tim Pietzcker,所以我可以確定有一個斜槓,當我連接文件夾字符串與文件名 – ohho 2010-04-29 09:42:33

回答

91

os.path.join(path, '')將添加斜線,如果它不是已經存在。

你可以做os.path.join(path, '', '')os.path.join(path_with_a_trailing_slash, ''),你仍然只會得到一個斜線。

7

您可以通過手動做到這一點:

path = ... 

import os 
if not path.endswith(os.path.sep): 
    path += os.path.sep 

但是,它通常是更清潔的使用os.path.join

+0

'os.path.join'+1 – 2012-12-30 04:21:23

43
os.path.normpath(mypath) + os.sep 
+0

謝謝!清晰簡潔 – dopplesoldner 2013-07-23 14:20:47

+9

如果原始路徑是根目錄'',則會失敗, – mingxiao 2014-01-31 21:54:24

-1

你可以使用這樣的事情:

os.path.normcase(path) 
    Normalize the case of a pathname. On Unix and Mac OS X, this returns the path unchanged; on case-insensitive filesystems, it converts the path to lowercase. On Windows, it also converts forward slashes to backward slashes. 

否則,你可以找別的東西上this

22

由於要連接的目錄和文件名,使用

os.path.join(directory, filename) 

如果你想擺脫.\..\..\blah\路徑,使用

os.path.join(os.path.normpath(directory), filename)