问题:Python,在目录字符串中添加尾部斜线,独立于操作系统

如果尾部斜杠尚不存在,如何在目录字符串中添加尾部斜杠(/对于* nix,\对于win32)?谢谢!

How can I add a trailing slash (/ for *nix, \ for win32) to a directory string, if the tailing slash is not already there? Thanks!


回答 0

os.path.join(path, '') 如果末尾不存在斜线,则会添加该斜线。

你可以做os.path.join(path, '', '')os.path.join(path_with_a_trailing_slash, '')你仍然只会得到一个尾部的斜杠。

os.path.join(path, '') will add the trailing slash if it’s not already there.

You can do os.path.join(path, '', '') or os.path.join(path_with_a_trailing_slash, '') and you will still only get one trailing slash.


回答 1

由于要连接目录和文件名,请使用

os.path.join(directory, filename)

如果要摆脱.\..\..\blah\路径,请使用

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

Since you want to connect a directory and a filename, use

os.path.join(directory, filename)

If you want to get rid of .\..\..\blah\ paths, use

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

回答 2

您可以通过以下方式手动进行操作:

path = ...

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

但是,通常使用起来更清洁os.path.join

You can do it manually by:

path = ...

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

However, it is usually much cleaner to use os.path.join.


回答 3

您可以使用如下形式:

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.

否则,您可以在页面上寻找其他内容

You could use something like this:

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.

Else you could look for something else on this page


声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。