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 中编写文件路径的首选方法是什么


- python-m http.server 443--使用SSL? 2022-01-01
- 如何在 python3 中将 OrderedDict 转换为常规字典 2022-01-01
- pytorch 中的自适应池是如何工作的? 2022-07-12
- python check_output 失败,退出状态为 1,但 Popen 适用于相同的命令 2022-01-01
- 沿轴计算直方图 2022-01-01
- padding='same' 转换为 PyTorch padding=# 2022-01-01
- 使用Heroku上托管的Selenium登录Instagram时,找不到元素';用户名'; 2022-01-01
- 如何将一个类的函数分成多个文件? 2022-01-01
- 分析异常:路径不存在:dbfs:/databricks/python/lib/python3.7/site-packages/sampleFolder/data; 2022-01-01
- 如何在 Python 的元组列表中对每个元组中的第一个值求和? 2022-01-01