我应该如何在python字符串字面上编写Windows路径?

发布于 2025-01-31 05:31:49 字数 152 浏览 3 评论 0 原文

假设我需要参考路径 c:\ meshes \ as 。如果我尝试直接编写,例如“ C:\ meshes \ as” ,我会遇到问题 - 某些异常,或者该路径不起作用。这是因为 \ 是逃生角色吗?我应该如何写路径?

Suppose I need to refer to the path C:\meshes\as. If I try writing that directly, like "C:\meshes\as", I encounter problems - either some exception, or the path just doesn't work. Is this because \ is acting as an escape character? How should I write the paths?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

冰雪之触 2025-02-07 05:31:49

您可以始终使用:

'C:/mydir'

这在Linux和Windows中都起作用。

另一种可能性是:

'C:\\mydir'

如果您有一些名称的问题,也可以尝试原始字符串文字:

r'C:\mydir'

但是,最好的做法是使用

os.path.join(mydir, myfile)

从python 3.4您也可以使用 pathlib 模块。这等同于上述:

pathlib.Path(mydir, myfile)

或:

pathlib.Path(mydir) / myfile

You can use always:

'C:/mydir'

This works both in Linux and Windows.

Another possibility is:

'C:\\mydir'

If you have problems with some names you can also try raw string literals:

r'C:\mydir'

However, the best practice is to use the os.path module functions that always joins with the correct path separator (os.path.sep) for your OS:

os.path.join(mydir, myfile)

From python 3.4 you can also use the pathlib module. This is equivalent to the above:

pathlib.Path(mydir, myfile)

or:

pathlib.Path(mydir) / myfile
疾风者 2025-02-07 05:31:49

使用 OS.Path 模块。

os.path.join( "C:", "meshes", "as" )

或使用原始字符串,

r"C:\meshes\as"

我也建议路径或文件名中的空格。而且您可以在字符串中使用双重斜线。

"C:\\meshes\\as.jpg"

Use the os.path module.

os.path.join( "C:", "meshes", "as" )

Or use raw strings

r"C:\meshes\as"

I would also recommend no spaces in the path or file names. And you could use double backslashes in your strings.

"C:\\meshes\\as.jpg"
她比我温柔 2025-02-07 05:31:49

是的, \ 在Python字符串文字中表示逃生序列的开始。在您的路径中,您有一个有效的双字符逃逸序列 \ a ,该> 折叠成 ascii bell

>>> '\a'
'\x07'
>>> len('\a')
1
>>> 'C:\meshes\as'
'C:\\meshes\x07s'
>>> print('C:\meshes\as')
C:\meshess

其他常见的逃生序列包括 \ t (tab), \ n (line feed) , \ r (返回马车):

>>> list('C:\test')
['C', ':', '\t', 'e', 's', 't']
>>> list('C:\nest')
['C', ':', '\n', 'e', 's', 't']
>>> list('C:\rest')
['C', ':', '\r', 'e', 's', 't']

如您所见,在所有这些示例中,backslash和文字中的下一个字符被分组在一起以在最终字符串中形成一个单个字符。 Python的逃生序列的完整列表是在这里

有多种处理方法:

  1. python不会在字符串文字中处理 r r < /code>或 r

     &gt;&gt;&gt; r'c:\ meshes \ as'
    'c:\\网格\\ as'
    &gt;&gt;&gt;打印(r'c:\ meshes \ as')
    C:\ meshes \ as
     

  2. Windows上的python也应处理前向斜线。

  3. 您可以使用 os.path。加入 ...

     &gt;&gt;&gt;导入操作系统
    &gt;&gt;&gt; OS.Path.join('C:',OS.Sep,'Meshes','as')
    'c:\\网格\\ as'
     
  4. ...或新的 pathlib 模块

     &gt;&gt;&gt;从pathlib导入路径
    &gt;&gt;&gt;路径('c:','/','网格','as')
    WindowsPath('C:/网格/as')
     

Yes, \ in Python string literals denotes the start of an escape sequence. In your path you have a valid two-character escape sequence \a, which is collapsed into one character that is ASCII Bell:

>>> '\a'
'\x07'
>>> len('\a')
1
>>> 'C:\meshes\as'
'C:\\meshes\x07s'
>>> print('C:\meshes\as')
C:\meshess

Other common escape sequences include \t (tab), \n (line feed), \r (carriage return):

>>> list('C:\test')
['C', ':', '\t', 'e', 's', 't']
>>> list('C:\nest')
['C', ':', '\n', 'e', 's', 't']
>>> list('C:\rest')
['C', ':', '\r', 'e', 's', 't']

As you can see, in all these examples the backslash and the next character in the literal were grouped together to form a single character in the final string. The full list of Python's escape sequences is here.

There are a variety of ways to deal with that:

  1. Python will not process escape sequences in string literals prefixed with r or R:

    >>> r'C:\meshes\as'
    'C:\\meshes\\as'
    >>> print(r'C:\meshes\as')
    C:\meshes\as
    
  2. Python on Windows should handle forward slashes, too.

  3. You could use os.path.join ...

    >>> import os
    >>> os.path.join('C:', os.sep, 'meshes', 'as')
    'C:\\meshes\\as'
    
  4. ... or the newer pathlib module

    >>> from pathlib import Path
    >>> Path('C:', '/', 'meshes', 'as')
    WindowsPath('C:/meshes/as')
    
愿得七秒忆 2025-02-07 05:31:49

使用路径

from pathlib import Path
data_folder = Path("source_data/text_files/")
file_to_open = data_folder / "raw_data.txt"
print(file_to_open.read_text())

路径采用类似路径的字符串,并调整当前操作系统的所有内容,无论是Windows还是Linux。例如,在Linux上,它将将所有后斜线转换为前向斜线,在窗口上,它将进行反向。

全文: python 3快速提示:处理Windows,Mac和Linux上的文件路径的简便方法


我的经验:

  • 我使用 OS.Path花了6个月的时间。加入(...),然后切换到 normpath(...),然后最终切换到 path(...)。使用了这三个,道路是所有世界中最好的。

  • 清洁器。
  • 少于打字。
  • 易于阅读路径(即更可读性)。
  • 可以使用/(见上文)连接两个不同的路径。
  • 更现代。

  • 可以使用/加入路径,而不是必须返回 os.path.join(...),并带有嵌套的Normpath调用来修复问题。
  • 清洁工。
  • 少于打字。
  • 易于阅读路径(即更可读性)。
  • 在Linux和Windows之间移植时错误的机会更少。
  • 更现代。

Use Path:

from pathlib import Path
data_folder = Path("source_data/text_files/")
file_to_open = data_folder / "raw_data.txt"
print(file_to_open.read_text())

Path takes a path-like string and adjusts everything for the current OS, either Windows or Linux. For example, on Linux it would convert all backslashes to forward slashes, and on Windows it would do the reverse.

Full article: Python 3 Quick Tip: The easy way to deal with file paths on Windows, Mac and Linux


My experience:

  • I spent 6 months using os.path.join(...), then switched to normpath(...) then finally switched to Path(...). Having used all three, Path is the best of all worlds.

Advantages of Path over os.path.join(...):

  • Cleaner.
  • Less typing.
  • Easier to read the paths (i.e. more readable).
  • Can join two different paths using / (see above).
  • More modern.

Advantages of Path over normpath(...):

  • Can join paths using / rather than having to fall back to os.path.join(...), with nested normpath calls to fix things up.
  • Cleaner.
  • Less typing.
  • Easier to read the paths (i.e. more readable).
  • Less chance of bugs when porting between Linux and Windows.
  • More modern.
听你说爱我 2025-02-07 05:31:49

Python Raw String是通过将字符串字面的字符串与“ R”或“ R”结合在一起而创建的。 Python Raw String将Backslash()视为字面角色。当我们想要一个包含后斜切并且不希望将其视为逃生角色的字符串时,这很有用。

手动执行:

WindowsPath("C:\meshes\as")

或使用R或R:

WindowsPath(r'C:/meshes/as')

Python raw string is created by prefixing a string literal with ‘r’ or ‘R’. Python raw string treats backslash () as a literal character. This is useful when we want to have a string that contains backslash and don’t want it to be treated as an escape character.

Doing Manually Such as:

WindowsPath("C:\meshes\as")

or by using r or R:

WindowsPath(r'C:/meshes/as')
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文