python-3.x - 带有转义字符错误的 Python Windows 路径
问题描述
我有一个存储在名为“a”的变量中的 Windows 路径。当我尝试在代码中打印或使用它时,以某种方式将一些特殊字符添加到字符串中。
>>> import re
>>> from pathlib import Path
>>>
>>>
>>> a = "E:\POC\testing\functionalities\logs\timer.logs"
>>> a
'E:\\POC\testing\x0cunctionalities\\logs\timer.logs'
>>>
>>> Path(a)
WindowsPath('E:/POC\testing\x0cunctionalities/logs\timer.logs')
>>> Path.absolute(a)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "c:\program files (x86)\python38-32\lib\pathlib.py", line 1159, in absolute
if self._closed:
AttributeError: 'str' object has no attribute '_closed'
>>>
>>> re.escape(a)
'E:\\\\POC\\\testing\\\x0cunctionalities\\\\logs\\\timer\\.logs'
>>>
>>> a.replace("\\", "/")
'E:/POC\testing\x0cunctionalities/logs\timer.logs'
>>> a.__repr__()
"'E:\\\\POC\\testing\\x0cunctionalities\\\\logs\\timer.logs'"
>>>
我能够处理所有特殊字符,但\f 以某种方式更改为 \x0c。
一种解决方案是将r添加到字符串中,但我的路径存储在变量中。我怎样才能做到这一点?我正在使用 python 3.8.5 和 Windows 10
>>> a = r"E:\POC\testing\functionalities\logs\timer.logs"
>>> a
'E:\\POC\\testing\\functionalities\\logs\\timer.logs'
>>>
>>>
>>> a = "E:\POC\testing\functionalities\logs\timer.logs"
>>> a = r"" + a
>>> a
'E:\\POC\testing\x0cunctionalities\\logs\timer.logs'
>>>
解决方案
根据您在@user8086906 帖子下的评论,您就不能这样做吗
a.replace('\\', '\')
? 我看到您在上面尝试过a.replace("\\", "/")
-您能解释一下期望的行为是什么吗?在我的机器上,我发布的第一个片段有效。
编辑:
谢谢@Gopirengaraj C - 我明白了现在的问题。问题在于它\f
是 Unicode 中的转义字符——更具体地说,它被称为“换页符”。我认为解决这个问题的一个好方法是避免replace
并做这样的事情:
a = r'{0}'.format(a)
Lmk 如果可行的话。
推荐阅读
- javascript - 访问 Google Apps 脚本中已解析的嵌套 JSON 中的对象
- json - pyspark.sql 转 JSON
- google-cloud-platform - REST API 和 Google Cloud Endpoints 之间的关系?
- javascript - 多个ajax倒计时的建议(每秒调用)
- python-2.7 - 如何修复 Python cx_Oracle 中的“ORA-19011”错误
- python - Python - 如何使用 Python 发送 html 电子邮件并附加图像?
- echarts - 在echarts中使用字典对象作为数据有什么好处吗?
- bitbucket - terraform validate 错误:参数“region”是必需的,但未设置
- ruby-on-rails - Rails 多态关联子不同列
- python - 使用 allauth get_login_redirect_url 登录后无法重定向到正确的 URL