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 中编写文件路径的首选方法是什么
基础教程推荐
- Discord.py 缺少必需的参数 2022-01-01
- numpy float:比算术运算中内置的慢 10 倍? 2022-01-01
- 用 Python 编写 Fortran 无格式文件 2022-01-01
- 使用生成器和迭代器时 Python 多循环失败 2022-01-01
- 尝试制作WhatsApp机器人 2022-01-01
- pyserial - 可以从线程 a 写入串行端口,是否阻塞从线程 b 读取? 2022-01-01
- 由Python将MP3转换为MIDI(类型错误:无法加载插件:mtg-Melodia:Melodia) 2022-01-01
- 将 x 轴刻度更改为自定义字符串 2022-01-01
- 与常规 dict 相比,Python manager.dict() 非常慢 2022-01-01
- 在 Celery 工作人员中捕获 Heroku SIGTERM 以优雅地关 2022-01-01
