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

筅森魡賤 提交于 2019-12-24 07:29:06

问题


How to pass string to pathlib.Path in Python3. I am dynamically passing normal windows path in Path(). 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.

Is there anyway to pass normal string to Path and check for its existence,

How to achieve this in windows?


回答1:


regular text is throwing an error because \ is an escape character in Python , you need to escape it by doubling it like so:

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

the raw text version doesn't check for escape characters and so does not throw an error.




回答2:


This will work

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

\N is a Python literal, you need to escape \ or use

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


来源:https://stackoverflow.com/questions/54746407/getting-os-error-when-passing-string-to-pathlib-path-in-windows

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!