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?
Answer
The issue arises because in Python, backslashes (\
) in normal strings are treated as escape characters, unless the string is prefixed with r
(raw string).
Problem with src
In the line:
src = "C:\Documents\Newsletters\Summer2018.pdf"
The \D
, \N
, etc., are interpreted as escape sequences. For example:
\D
is not a valid escape sequence, so Python throws an error.\n
is treated as a newline character.
Solutions
1. Escape the Backslashes
If you want to use a normal string, you need to escape each backslash (\\
):
src = "C:\\Documents\\Newsletters\\Summer2018.pdf"
s = pathlib.Path(src)
print(s.exists()) # Should work
2. Use a Raw String
Raw strings treat backslashes as literal characters:
src = r"C:\Documents\Newsletters\Summer2018.pdf"
s = pathlib.Path(src)
print(s.exists()) # Should work
3. Use os.path.normpath
If you have a string that might contain backslashes, you can normalize it using os.path.normpath
to ensure compatibility:
import os
import pathlib
src = "C:/Documents/Newsletters/Summer2018.pdf" # Forward slashes are safe
src_normalized = os.path.normpath(src)
s = pathlib.Path(src_normalized)
print(s.exists()) # Should work
This method is especially useful when your string uses forward slashes (/
), as they are automatically converted to backslashes (\
) on Windows.
4. Use Forward Slashes
Forward slashes (/
) are automatically interpreted correctly on Windows:
src = "C:/Documents/Newsletters/Summer2018.pdf"
s = pathlib.Path(src)
print(s.exists()) # Should work
Summary
To pass a normal string to Path
:
- Use escaped backslashes (
\\
) or forward slashes (/
). - For dynamic strings, consider normalizing them with
os.path.normpath
.
Example:
import pathlib
src = "C:/Documents/Newsletters/Summer2018.pdf" # or "C:\\Documents\\Newsletters\\Summer2018.pdf"
s = pathlib.Path(src)
print(s.exists())