如果目录字符串中没有尾部斜杠,那么如何将尾部斜杠(/表示 * nix,\表示 win32)添加到目录字符串中?谢谢!
/
\
你可以通过以下方式手动完成:
path = ... import os if not path.endswith(os.path.sep): path += os.path.sep
然而,使用 os.path.join通常要干净得多。
os.path.join
你可以用这样的东西:
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.
否则,你可以在 这个页面上寻找其他内容
由于要连接目录和文件名,请使用
os.path.join(directory, filename)
如果要去掉 .\..\..\blah\路径,请使用
.\..\..\blah\
os.path.join(os.path.normpath(directory), filename)
如果后面还没有斜杠,os.path.join(path, '')将添加它。
os.path.join(path, '')
你可以选择 os.path.join(path, '', '')或者 os.path.join(path_with_a_trailing_slash, ''),但是你仍然只能得到一个斜杠。
os.path.join(path, '', '')
os.path.join(path_with_a_trailing_slash, '')