python - File paths in python, possible writing styles
问题描述
I know that the following string definitions represent (python internal) the same (basic knowledge):
s1 = "D:\\users\\xy\\Desktop\\PC_daten.txt"
s2 = r"D:\users\xy\Desktop\PC_daten.txt"
Therefore if you make it e.g. interactive in PythonWin:
>>> s1 = "D:\\users\\xy\\Desktop\\PC_daten.txt"
>>> s1
'D:\\users\\xy\\Desktop\\PC_daten.txt'
>>> print s1
D:\users\xy\Desktop\PC_daten.txt
>>> s2 = r"D:\users\xy\Desktop\PC_daten.txt"
>>> s2
'D:\\users\\xy\\Desktop\\PC_daten.txt'
>>> print s2
D:\users\xy\Desktop\PC_daten.txt
Clear for me (understand)
But what me confuse is that at the python built in function open all this (partly crazy) path-codings work (interactive tested in PythonWin):
>>> a = open("D:\users\xy\Desktop\PC_daten.txt")
>>> a
<open file 'D:\\users\\xy\\Desktop\\PC_daten.txt', mode 'r' at 0x00000000046989C0>
>>> b = open("D:\\users\\xy\\Desktop\\PC_daten.txt")
>>> b
<open file 'D:\\users\\xy\\Desktop\\PC_daten.txt', mode 'r' at 0x00000000048B2300>
>>> c = open(r"D:\users\xy\Desktop\PC_daten.txt")
>>> c
<open file 'D:\\users\\xy\\Desktop\\PC_daten.txt', mode 'r' at 0x00000000048B20C0>
>>> d = open(r"D:\\users\\xy\\Desktop\\PC_daten.txt")
>>> d
<open file 'D:\\\\users\\\\xy\\\\Desktop\\\\PC_daten.txt', mode 'r' at 0x00000000048B2390>
My questions:
- Where is this behaviour documented?
- Have anybody background-informations?
Tests was made at Windows 7 OS and with PythonWin 2.7.13
解决方案
此字符串行为记录在(Python v3.7 文档)下2.4.1. String and Bytes literals
, 的行为open()
记录在2. Built-in Functions
.
具体来说,对于文件/路径,在条目中的 、open()
下进行了说明。诚然,要真正理解这个参数需要大量阅读。16.1.2. Process Parameters
class os.PathLike
总之:一个 r"string" 是一个原始字符串。使用原始斜杠时,您不需要像\\
产生单个斜杠那样转义斜杠。\
在第二个块中,为了清楚起见,您正在查看变量本身并通过它们的字符串表示(使用 print 时)查看它们(我认为您提到您理解得很好,但我只是想重复一遍给您为了确定)。
展望未来,python 版本在处理文件和文件夹时都将使用 PathLike 对象。我猜您仍在使用 Python 2.x,因为您在运行时没有收到错误print s1
- 应该print(s1)
在 Python 3.x 中。我建议尽快迁移到 Python 3,它确实好多了。
我希望这能成功回答你的问题?
推荐阅读
- google-app-engine - GCP 内部负载平衡器
- java - Javassist 不调用超类中定义的方法
- dart - 我可以在渡槽响应控制器中调用任何飞镖函数吗?
- android - 管道:支持的最低 Gradle 版本为 4.10.1。当前版本是 4.4
- c# - 最小化十进制 .csv 文件的文件大小
- excel - 仅当文本不是英文时才谷歌翻译文本
- awk - 比较 2 个文件中的字段并仅写入缺失或不同的字段
- excel - 在将 Excel 表格粘贴到文档中之前“取消”Word 样式
- angular - 输入文件无法正常工作,代替 ngFor
- odbc - [Microsoft][ODBC Driver Manager] 未找到数据源名称且未指定默认驱动程序 [Dynamics GP]