Windows 文件路径中的反斜杠? [英] Backslashes in Windows filepath?

查看:45
本文介绍了Windows 文件路径中的反斜杠?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Python for WINdows中设置字符串到文件路径时,是否需要格式化为:

When setting a string to a filepath in Python for WIndows, does it need to be formatted as:

C:\\Users\\

或者转义在 Windows 上不适用吗?我的脚本目前在 import os 行中给了我类似非 ASCII 字符"的信息,所以我无法真正测试它.

Or do escapes not apply on Windows? My script is currently giving me something like "Non-ASCII character" at the line import os, so I can't really test this.

推荐答案

简短回答:按照 gnibbler 的建议使用正斜杠.

Short answer: Use forward slash instead as suggested by gnibbler.

关于使用原始字符串:

使用原始字符串通常工作正常,但您仍然必须注意 r"\"" 转义引号字符.也就是说,原始字符串不是绝对原始的这就是为什么不能在像 '\' 这样的字符串末尾使用反斜杠(或任何奇数个反斜杠)的原因(反斜杠会转义以下引号字符).

Using a raw string usually works fine, still you have to note that r"\"" escapes the quoute char. That is, raw string is not absolutely raw and thats the reason why you cant use backslash (or any odd number of backslashes) in the end of a string like '\' (the backslash would escape the following quote character).

In [9]: a=r'\\'

In [10]: b=r'\\\'
  File "<ipython-input-10-9f86439e68a3>", line 1
    b=r'\\\'
             ^
SyntaxError: EOL while scanning string literal


In [11]: a
Out[11]: '\\\\'

这篇关于Windows 文件路径中的反斜杠?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆