You can use always:

'C:/mydir'

This works both in Linux and Windows.

Another possibility is:

'C:\\mydir'

If you have problems with some names you can also try raw string literals:

r'C:\mydir'

However, the best practice is to use the os.path module functions that always joins with the correct path separator (os.path.sep) for your OS:

os.path.join(mydir, myfile)

From python 3.4 you can also use the pathlib module. This is equivalent to the above:

pathlib.Path(mydir, myfile)

or:

pathlib.Path(mydir) / myfile
Answer from joaquin on Stack Overflow
🌐
Reddit
reddit.com › r/learnpython › windows path to python path
r/learnpython on Reddit: Windows path to Python path
February 2, 2022 -

I have been searching the web for a solution without a result.
I made this small script that can be used. Feel free to use it.
I wonder is there a better solution on the issue to convert windows path to python path?

"""
A path, in Windows "C:\Folder" . in Python it is "C:/Folder".
In Python the "\" character can get interpreted as the ESCAPE character.
When an 'r' or 'R' prefix is present, a character following a backslash is
included in the string without change, and all backslashes are left in the string.
"""
def main():
# - YOUR INPUT - IMPORTANT: keep the r in front of path string here.
win_path = r"<TYPE YOUR PATH HERE>"
# Call function to convert from windows to Python path.
path_py = py_path(win_path)
print("Your Python Path: ", path_py)

def py_path(win_path):
python_path = "" # The result of this script.
# Convert to ASCII list
ascii_values_list = []
for character in win_path:
ascii_values_list.append(ord(character))
# Replace all ASCII values for "\" (=92) with value for "/" (=47).
for i in range(0, len(ascii_values_list)):
if ascii_values_list[i] == 92:
ascii_values_list[i] = 47
path_py = "" # Convert ASCII list to string
for val in ascii_values_list:
path_py = path_py + chr(val)

if path_py[-1] != "/": # Add "/" at end of path if needed.
path_py = path_py + "/"
return path_py

if __name__ == "__main__":
main() # Script goes there.

# EOF

Discussions

python - Convert WindowsPath to String - Stack Overflow
Is there a way that I can convert WindowsPath to string so that I can glob all the files into one list? ... Which line of code? You have more info than we do. ... try type(parent_dir), I think it is WindowsPath (not str). + operation failing due to different types. ... Two things to consider: pathlib supports glob: clickme and also relative paths, which can be resolved like Path(...).resolve() ... As most other Python ... More on stackoverflow.com
🌐 stackoverflow.com
Python - handling windows path with '\' characters
Hi, I’ve been struggling with windows path for a while because of Python regex. When I need my user to input a path variable in a tool, if they give a classical windows path Python will convert ‘’ because of regex. os.path.normpath don’t seem to work. path = 'L:\sandbox\20_lookdev\... More on tech-artists.org
🌐 tech-artists.org
0
0
December 9, 2019
Implement Path property that returns the full path as a string - Ideas - Discussions on Python.org
pathlib already provides multiple methods / properties which return things as a str object the reasoning is that It is kind of odd that you have a ton of properties that give you parts of the path, but no property that gives you the whole path pathlib.PurePath.name for example I propose an ... More on discuss.python.org
🌐 discuss.python.org
0
October 13, 2024
How to Convert string variable to Raw literal path in Windows
Background Hello, I’m compiling Jython (Python2) on Windows. I want to convert a string variable to a raw string because I want to make a path for a photo or self-written module. Sample code This cord make a path and no problem with import self wrote module I can make a path if I directly ... More on forum.image.sc
🌐 forum.image.sc
4
0
February 23, 2021
🌐
Sentry
sentry.io › sentry answers › python › handle windows paths in python
Handle Windows paths in Python | Sentry
September 15, 2024 - This approach has the advantage ... path strings work across platforms. For example, the path sam/Documents/data/1.5/data.csv could be resolved to /home/sam/Documents/data/1.5/data.csv on a Linux system or C:\Users\sam\Documents\data\1.5\data.csv on a Windows system, as long as the script is executed in /home/ or C:\Users. In a standard Python string, the ...
🌐
Python
docs.python.org › 3 › library › os.path.html
os.path — Common pathname manipulations
On systems which do not use drive specifications, drive will always be the empty string. In all cases, drive + tail will be the same as path. On Windows, splits a pathname into drive/UNC sharepoint and relative path.
🌐
b.telligent
btelligent.com › en › blog › best-practice-working-with-paths-in-python-part-1-2
Best Practice: Working With Paths In Python (Part 1)
C and D are somewhat better, since they use string formatting, but they still do not resolve the system-dependence problem. If I apply the result under Windows, I get a functional, but inconsistent path with a mixture of separators. filename = "some_file" print("{}/{}".format(path_dir, filename)) ...: 'C:\\Users\\sselt\\Documents\\blog_demo/some_file' A solution from Python is os.sep or os.path.sep.
Top answer
1 of 2
53

As most other Python classes do, the WindowsPath class, from pathlib, implements a non-defaulted "dunder string" method (__str__). It turns out that the string representation returned by that method for that class is exactly the string representing the filesystem path you are looking for. Here an example:

from pathlib import Path

p = Path('E:\\x\\y\\z')
>>> WindowsPath('E:/x/y/z')

p.__str__()
>>> 'E:\\x\\y\\z'

str(p)
>>> 'E:\\x\\y\\z'

The str builtin function actually calls the "dunder string" method under the hood, so the results are exaclty the same. By the way, as you can easily guess calling directly the "dunder string" method avoids a level of indirection by resulting in faster execution time.

Here the results of the tests I've done on my laptop:

from timeit import timeit

timeit(lambda:str(p),number=10000000)
>>> 2.3293891000000713

timeit(lambda:p.__str__(),number=10000000)
>>> 1.3876856000000544

Even if calling the __str__ method may appear a bit uglier in the source code, as you saw above, it leads to faster runtimes.

2 of 2
4

You are right, you need a string when you call glob.glob. In the last line of your code, parent_dir is a pathlib.Path object, which you cannot concatenate with the string '/*fits'. You need to explicitly convert parent_dir to a string by passing it to the built-in str function.

The last line of your code should thus read:

fspec = glob.glob(str(parent_dir)+'/*fits')

To illustrate further, consider this example:

>>> from pathlib import Path
>>> path = Path('C:\\')
>>> path
WindowsPath('C:/')
>>> str(path)
'C:\\'
>>>
🌐
Tech-Artists.Org
tech-artists.org › t › python-handling-windows-path-with-characters › 12045
Python - handling windows path with '\' characters - Tech-Artists.Org
December 9, 2019 - Hi, I’ve been struggling with windows path for a while because of Python regex. When I need my user to input a path variable in a tool, if they give a classical windows path Python will convert ‘’ because of regex. os.path.normpath don’t seem to work. path = 'L:\sandbox\20_lookdev\10_asset\character\assetName\model\scenes\publish' os.path.normpath(path) >>>> 'L:\\sandbox\x10_lookdev\x08_asset\\character\x07ssetName\\model\\scenes\\publish' # I modified the function ‘rawString’ found on the...
Find elsewhere
🌐
Python.org
discuss.python.org › ideas
Implement Path property that returns the full path as a string - Ideas - Discussions on Python.org
October 13, 2024 - pathlib already provides multiple methods / properties which return things as a str object the reasoning is that It is kind of odd that you have a ton of properties that give you parts of the path, but no property that gives you the whole path pathlib.PurePath.name for example I propose an Pathobj.fullpath or Pathobj.full_path property be added this should result in the same operation as str(Pathobj) so that Pathobj.resolve().full_path can also work
🌐
Python
docs.python.org › 3 › library › pathlib.html
pathlib — Object-oriented filesystem paths
February 23, 2026 - This method is string-based; it neither accesses the filesystem nor treats “..” segments specially. The following code is equivalent: >>> u = PurePath('/usr') >>> u == p or u in p.parents False · Added in version 3.9. Deprecated since version 3.12, removed in version 3.14: Passing additional arguments is deprecated; if supplied, they are joined with other. ... With PureWindowsPath, return True if the path is considered reserved under Windows, False otherwise.
🌐
Iditect
iditect.com › faq › python › how-to-write-a-windows-path-in-a-python-string-literal.html
How to write a Windows path in a Python string literal?
In Python, you can write a Windows path in a string literal by using either single backslashes (\) or double backslashes (\\) as the path separator. Windows supports both single and double backslashes for representing file paths.
🌐
Medium
medium.com › @ageitgey › python-3-quick-tip-the-easy-way-to-deal-with-file-paths-on-windows-mac-and-linux-11a072b58d5f
Python 3 Quick Tip: The easy way to deal with file paths on Windows, Mac and Linux | by Adam Geitgey | Medium
January 31, 2018 - And Python’s support for mixing slash types is a Windows-only hack that doesn’t work in reverse. Using backslashes in code will totally fail on a Mac: For all these reasons and more, writing code with hardcoded path strings is the kind of thing that will make other programmers look at you ...
🌐
Reddit
reddit.com › r/learnpython › windows path 2 python path
r/learnpython on Reddit: Windows Path 2 Python Path
February 2, 2022 -

I have been searching the web for a solution without a result.
I made this small script that can be used. Feel free to use it.
I wonder is there a better solution on the issue to convert windows path to python path?

"""
A path, in Windows "C:\Folder" . in Python it is "C:/Folder".
In Python the "\" character can get interpreted as the ESCAPE character.
When an 'r' or 'R' prefix is present, a character following a backslash is
included in the string without change, and all backslashes are left in the string.
"""
def main():
# - YOUR INPUT - IMPORTANT: keep the r in front of path string here.
win_path = r"<TYPE YOUR PATH HERE>"
# Call function to convert from windows to Python path.
path_py = py_path(win_path)
print("Your Python Path: ", path_py)

def py_path(win_path):
python_path = "" # The result of this script.
# Convert to ASCII list
ascii_values_list = []
for character in win_path:
ascii_values_list.append(ord(character))
# Replace all ASCII values for "\" (=92) with value for "/" (=47).
for i in range(0, len(ascii_values_list)):
if ascii_values_list[i] == 92:
ascii_values_list[i] = 47
path_py = "" # Convert ASCII list to string
for val in ascii_values_list:
path_py = path_py + chr(val)

if path_py[-1] != "/": # Add "/" at end of path if needed.
path_py = path_py + "/"
return path_py

if __name__ == "__main__":
main() # Script goes there.

# EOF

🌐
Automate the Boring Stuff
automatetheboringstuff.com › chapter8
Automate the Boring Stuff with Python
Calling os.path.basename(path) will return a string of everything that comes after the last slash in the path argument. The dir name and base name of a path are outlined in Figure 8-4. Figure 8-4. The base name follows the last slash in a path and is the same as the filename.
🌐
sqlpey
sqlpey.com › python › solved-how-to-properly-write-a-windows-path-in-a-python-string-literal
Solved: How to Properly Write a Windows Path in a Python String Literal
December 5, 2024 - Using Forward Slashes: Python on Windows can often handle paths with forward slashes (/) as well as backslashes. path = "C:/meshes/as" print(path) # Outputs: C:/meshes/as · Environment Variables: You can also construct paths using environment variables for greater flexibility. Combining Paths: Use the pathlib method of combining paths for cleaner code instead of string concatenations.
🌐
Homedutech
homedutech.com › faq › python › convert-windowspath-to-string-in-python.html
Convert WindowsPath to String in python
This code snippet demonstrates how to convert a WindowsPath object path to a string path_str using the str() function. "Python pathlib WindowsPath to string conversion" Description: Users might be specifically looking for a solution using the pathlib module to convert a WindowsPath object to a string.
🌐
Towards Data Science
towardsdatascience.com › home › latest › path representation in python
Path Representation in Python | Towards Data Science
January 15, 2025 - If you’re using strings to represent paths, you’ll need to write conditional logic to handle different operating systems. Not only does this make your code messy, but it also introduces unnecessary complexity. # This is a bad practice import platform if platform.system() == 'Windows': filepath = 'C:homethisisapathtoadirectory' else: # e.g.
🌐
Real Python
realpython.com › add-python-to-path
How to Add Python to PATH – Real Python
January 30, 2023 - Each path in PATH is separated by a colon or a semicolon—a colon for UNIX-based systems and a semicolon for Windows. It’s like a Python variable with a long string as its value.