简体   繁体   English

在Windows中将字符串传递给pathlib.Path时出现OS错误

[英]Getting OS Error when passing string to pathlib.Path in windows

How to pass string to pathlib.Path in Python3. 如何在Python3中将字符串传递给pathlib.Path I am dynamically passing normal windows path in Path(). 我在Path()中动态传递普通的Windows路径。 But it is throwing error. 但这会引发错误。

the snippet is as below: 片段如下:

src = "C:\Documents\Newsletters\Summer2018.pdf"
rsrc = r"C:\Documents\Newsletters\Summer2018.pdf"
s = pathlib.Path(src)
rs = pathlib.Path(rsrc)

print(s.exists())  #  throws error

print(rs.exists()) # returns True

I want to pass normal string to Path, instead off raw string. 我想将普通字符串传递给Path,而不是原始字符串。

Is there anyway to pass normal string to Path and check for its existence, 无论如何,有没有将普通的字符串传递给Path并检查其存在性,

How to achieve this in windows? 在Windows中如何实现呢?

regular text is throwing an error because \\ is an escape character in Python , you need to escape it by doubling it like so: 普通文本会引发错误,因为\\是Python中的转义字符,您需要通过将其加倍来对其进行转义,如下所示:

src = "C:\\Documents\\Newsletters\\Summer2018.pdf"

the raw text version doesn't check for escape characters and so does not throw an error. 原始文本版本不检查转义字符,因此不会引发错误。

This will work 这会起作用

src ="C:\Documents\\Newsletters\Summer2018.pdf"

\\N is a Python literal, you need to escape \\ or use \\ N是Python文字,您需要转义\\或使用

r"C:\Documents\Newsletters\Summer2018.pdf"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM