在Python中编写文件路径的首选方法是什么? [英] What is the preferred way to write a file path in Python

查看:174
本文介绍了在Python中编写文件路径的首选方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Python中编写文件路径时,我已经看到了几种变体来编写语法,我很好奇是否只有一个首选方法:例子是:

<$ myFile = rC:\ My Documents \test\hello.txt
myFile =C:\\ My Documents \\ test\\ \\\hello.txt
myFile =C:/ My Documents / test / hello.txt

如果有人可以提供一些指导,将不胜感激。呵呵,就像一个信息,我写python的技巧水平是新手。

解决方案

第一和第二是完全等价的。第三个是字符数最短的。此外,在Windows以外的平台上也支持正斜杠作为路径分隔符。但是,如果您正在对特定于Windows的路径进行硬编码,则这并不重要。我会说,三者中的任何一个都是安全的。一个不正确的(容易出错的)方法是使用非转义的反斜杠:

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


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.

解决方案

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"

这篇关于在Python中编写文件路径的首选方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆