简体   繁体   English

用Python编写文件路径的首选方法是什么

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

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: 当用python编写文件路径时,我看到了几种变体来编写语法,并且我很好奇是否只有一种首选的方式:示例如下:

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. 哦,就像一个信息一样,我写python的技能水平是新手。

Like Lev Levitsky says, the third options is the best of the bunch. 就像列夫·列维茨基(Lev Levitsky)所说的那样,第三个选择是最好的选择。 It will work both on Windows and Linux. 它可以在Windows和Linux上运行。

To give this some authority you can read the django docs which recommend 要授予此权限,您可以阅读django文档 ,该文档建议

When specifying the path, always use forward slashes, even on Windows (eg C:/homes/user/mysite/sqlite3.db). 指定路径时,即使在Windows上也要始终使用正斜杠(例如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. 要添加更多评论,您还可以研究使用os.path.join()以独立于平台的方式智能地连接路径。

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. 此外,在Windows以外的平台上,也支持将正斜杠用作路径分隔符。 But that is not so important if you are hardcoding a Windows-specific path. 但是,如果要对Windows特定路径进行硬编码,那并不是那么重要。 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"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM