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

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

问题描述

在 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:

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

如果有人可以提供一些指导,将不胜感激.哦,顺便说一下,我写python的水平是新手.

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.

推荐答案

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

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	esthello.txt"

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

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