Question

When writing a file path in python, I have seen several variations to write the syntax and I was curious if there is just one preferred way: the examples are:

myFile= r"C:\My Documents\test\hello.txt"
myFile = "C:\\My Documents\\test\\hello.txt"
myFile = "C:/My Documents/test/hello.txt"

If someone could provide some guidance, it would greatly be appreciated. Oh, just as a for info, my skill level in writing python is novice.

Was it helpful?

Solution 2

The 1st and 2nd are completely equivalent. The third one is the shortest in terms of the character count. Also, forward slash is supported as path separator on platforms other than Windows, too. But that is not so important if you are hardcoding a Windows-specific path. I'd say, any of the three are safe. An incorrect (error-prone) way would be using unescaped backslashes:

myFile = "C:\My Documents\test\hello.txt"

OTHER TIPS

Like Lev Levitsky says, the third options is the best of the bunch. It will work both on Windows and Linux.

To give this some authority you can read the django docs which recommend

When specifying the path, always use forward slashes, even on Windows (e.g. C:/homes/user/mysite/sqlite3.db).

To add a further comment, you can also look into the use of use os.path.join() to intelligently join paths in a platform independent way.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top