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

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
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
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
Windows path to Python path
I wonder is there a better solution on the issue to convert windows path to python path? Yes; simply use pathlib. from pathlib import Path win_path = r"" path_universal = Path(win_path) print("Your Python Path: ", path_universal) The more you use it, the more you regret not knowing about it earlier. It's an awesome piece of kit in the standard library, probably my favourite. More on reddit.com
🌐 r/learnpython
4
2
February 2, 2022
🌐
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.
🌐
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 ...
🌐
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.
🌐
Reuven Lerner
lerner.co.il › home › blog › python › avoiding windows backslash problems with python’s raw strings
Avoiding Windows backslash problems with Python's raw strings — Reuven Lerner
July 24, 2018 - All you need to do is put an “r” before the opening quotes (single or double): >>> filename = r'c:\abc\def\ghi.txt' >>> print(filename) c:\abc\def\ghi.txt · Note that a “raw string” isn’t really a different type of string at all.
🌐
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 ...
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
🌐
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...
🌐
ArcGIS Pro
pro.arcgis.com › en › pro-app › latest › arcpy › get-started › setting-paths-to-data.htm
Setting paths to data in Python—ArcGIS Pro | Documentation
Programming languages, such as Python, treat a backslash (\) as an escape character. For instance, \n represents a line feed, and \t represents a tab. When specifying a path, a forward slash (/) can be used in place of a backslash. Two backslashes can be used instead of one to avoid a syntax error. A string ...
🌐
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.
🌐
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.
🌐
YouTube
youtube.com › codetwist
python windows path to string - YouTube
Download this code from https://codegive.com Title: Converting Windows Path to String in Python: A Comprehensive TutorialIntroduction:In Python, working with...
Published   December 27, 2023
Views   91
🌐
Python
docs.python.org › id › 3.9 › library › os.path.html
os.path --- Common pathname manipulations — Dokumentasi Python 3.9.24
Split the pathname path into a ... 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....
🌐
Real Python
realpython.com › videos › creating-path-objects-from-strings
Creating Path Objects From Strings (Video) – Real Python
You can either use a / instead, which means you can just represent a Windows path with the normal C:, but and then instead of using a \ like you normally would, you just use a / instead. 03:24 You can do that and the pathlib library knows what to do with that, and then correctly creates a Path object that points to this specific path. 03:33 Another way of doing it is to use raw string, and you can do that in Python by prefixing the string with just the r character, so you put this r in front of the string, and then you can use \ characters like you would normally with a Windows path.
Published   December 20, 2022
🌐
Data to Fish
datatofish.com › add-python-to-windows-path
How to Add Python to Windows PATH
That should open the Environment Variables window, where you can add/edit your paths. ... Click on New... if no Path variable is present, Otherwise select the Path variable and then click on Edit… instead. You should then see the New User Variable box. Type Path in the Variable name field. For the Variable value you will need to know the path to the Python that is installed on your computer.
🌐
Folkstalk
folkstalk.com › home › 2022 › october
Find Python Path Windows With Code Examples
October 4, 2022 - Manually Locate Where Python is Installed Type 'Python' in the Windows Search Bar. Right-click on the Python App, and then select “Open file location“ Right-click on the Python shortcut, and then select Properties. Click on “Open File Location“04-Mar-2022 · In order to obtain the Current Working Directory in Python, use the os. getcwd() method. This function of the Python OS module returns the string containing the absolute path to the current working directory.14-Jul-2022
🌐
Geek University
geek-university.com › home › python › add python to the windows path
Add Python to the Windows Path | Python#
June 25, 2022 - If you’ve installed Python in Windows using the default installation options, the path to the Python executable wasn’t added to the Windows Path variable. The Path variable lists the directories that will be searched for executables when you type a command in the command prompt.
🌐
Delft Stack
delftstack.com › home › howto › python › set file path python
How to Set File Path in Python | Delft Stack
February 14, 2024 - By concatenating these variables within the file_path string and using a raw string literal "C:\Users\Username\\" as the base, we create the complete file path. The output then displays this constructed path, ensuring that backslashes are treated as literal characters, maintaining their intended role as separators in a Windows file path.