1

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?

Klaus D.
  • 13,874
  • 5
  • 41
  • 48
rajeshkumargp
  • 105
  • 1
  • 11

2 Answers2

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.

vencaslac
  • 2,727
  • 1
  • 18
  • 29
  • The string is passed dynamically, Is there way to escape \ in Windows, I want to code so that it works irrescpective of OS. – rajeshkumargp Feb 18 '19 at 11:58
  • 1
    you can use the contents of this answer to determine what os the script is running on but i don't know that you can bypass the escape character in an elegant way https://stackoverflow.com/questions/1854/python-what-os-am-i-running-on – vencaslac Feb 18 '19 at 12:01
1

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"
lalam
  • 195
  • 1
  • 11