What is the preferred way to write a file path in Python

元气小坏坏 提交于 2019-11-29 17:38:51

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"

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!