首页 > 解决方案 > 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:

Tests was made at Windows 7 OS and with PythonWin 2.7.13

标签: pythonstringpathbackslash

解决方案


此字符串行为记录在(Python v3.7 文档)下2.4.1. String and Bytes literals, 的行为open()记录在2. Built-in Functions.
具体来说,对于文件/路径,在条目中的 、open()下进行了说明。诚然,要真正理解这个参数需要大量阅读。16.1.2. Process Parametersclass os.PathLike

总之:一个 r"string" 是一个原始字符串。使用原始斜杠时,您不需要像\\产生单个斜杠那样转义斜杠。\

在第二个块中,为了清楚起见,您正在查看变量本身并通过它们的字符串表示(使用 print 时)查看它们(我认为您提到您理解得很好,但我只是想重复一遍给您为了确定)。

展望未来,python 版本在处理文件和文件夹时都将使用 PathLike 对象。我猜您仍在使用 Python 2.x,因为您在运行时没有收到错误print s1- 应该print(s1)在 Python 3.x 中。我建议尽快迁移到 Python 3,它确实好多了。

我希望这能成功回答你的问题?


推荐阅读