文件路徑 - Windows 上的倒斜槓以及 macOS / Linux / UNIX 上的正斜槓

文件路徑 - Windows 上的倒斜槓以及 macOS / Linux / UNIX 上的正斜槓

1. 正斜槓 (斜槓 /) 和反斜槓 (倒斜槓 \)

Windows - 正斜槓,左斜槓,斜槓符號是 /
macOS / Linux / UNIX - 反斜槓,右斜槓,倒斜槓符號是 \

Windows 使用反斜槓 \ 的歷史來自 DOS。因爲 DOS 使用正斜槓 / 表示命令行參數,Windows 只能用反斜槓\ 表示路徑了。
Window 單詞的第一筆,即字母 W 的第一筆,就是反斜槓 \
Windows 文件瀏覽器使用反斜槓 \ 作爲路徑分隔符。

/ 撇是正斜槓,\ 捺是反斜槓。

2. 單反斜槓和雙反斜槓

在編程語言中反斜槓 \ 是轉義前導字符,\n 代表換行。當反斜槓 \ 用在字符串中時,要用雙反斜槓 \\

路徑名在編程語言中是字符串類型的,在路徑名中不能用 \ 表示路徑分割,單個 \ 表示轉義字符的含義,所以在字符串中要表示 \ 必須用雙斜槓 \\

../..\ 表示上一級路徑。
./.\ 表示當前路徑。

3. Windows

請注意,倒斜槓有兩個,因爲每個倒斜槓需要由另一個倒斜槓字符來轉義。

Microsoft Windows [版本 6.1.7601]
版權所有 (c) 2009 Microsoft Corporation。保留所有權利。

C:\Users\foreverstrong>python
Python 3.6.0 (v3.6.0:41df79263a11, Dec 23 2016, 08:06:12) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> os.path.join("usr", "include", "c++")
'usr\\include\\c++'
>>>
>>> print(os.path.join("usr", "include", "c++"))
usr\include\c++
>>>
>>>
>>> files = ["a.txt", "b.txt", "c.txt"]
>>> for filename in files:
...     print(os.path.join("C:\\Users\\Default", filename))
...
C:\Users\Default\a.txt
C:\Users\Default\b.txt
C:\Users\Default\c.txt
>>>

4. Linux

strong@foreverstrong:~$ python
Python 2.7.12 (default, Nov 19 2016, 06:48:10) 
[GCC 5.4.0 20160609] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> os.path.join("usr", "include", "c++")
'usr/include/c++'
>>> 
>>> print(os.path.join("usr", "include", "c++"))
usr/include/c++
>>> 
>>> 
>>> files = ["a.txt", "b.txt", "c.txt"]
>>> for filename in files:
...     print(os.path.join("/Users/Default", filename))
... 
/Users/Default/a.txt
/Users/Default/b.txt
/Users/Default/c.txt
>>> 
>>> 
>>> files = ["a.txt", "b.txt", "c.txt"]
>>> for filename in files:
...     print(os.path.join("/Users/Default/", filename))
... 
/Users/Default/a.txt
/Users/Default/b.txt
/Users/Default/c.txt
>>> 
>>> 
>>> files = ["a.txt", "b.txt", "c.txt"]
>>> for filename in files:
...     print(os.path.join("/Users/Default//", filename))
... 
/Users/Default//a.txt
/Users/Default//b.txt
/Users/Default//c.txt
>>> 
>>> 
>>> files = ["a.txt", "b.txt", "c.txt"]
>>> for filename in files:
...     print(os.path.join("/Users/Default///", filename))
... 
/Users/Default///a.txt
/Users/Default///b.txt
/Users/Default///c.txt
>>>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章