What is the preferred way to write a file path in Python(在 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 中编写文件路径的首选方法是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 Python 中编写文件路径的首选方法是什么
基础教程推荐
- 无法导入 Pytorch [WinError 126] 找不到指定的模块 2022-01-01
- 在Python中从Azure BLOB存储中读取文件 2022-01-01
- PermissionError: pip 从 8.1.1 升级到 8.1.2 2022-01-01
- 求两个直方图的卷积 2022-01-01
- 使用大型矩阵时禁止 Pycharm 输出中的自动换行符 2022-01-01
- 在同一图形上绘制Bokeh的烛台和音量条 2022-01-01
- 包装空间模型 2022-01-01
- PANDA VALUE_COUNTS包含GROUP BY之前的所有值 2022-01-01
- Plotly:如何设置绘图图形的样式,使其不显示缺失日期的间隙? 2022-01-01
- 修改列表中的数据帧不起作用 2022-01-01
