天天看點

Python在windows系統中表示檔案路徑

Windows系統中,路徑使用的是\。而Linux系統中,路徑使用/。\同時也是轉義字元,是以使用\的時候會有問題。

如果運氣好,\後沒有可以轉義的字元,還是可以正常輸出:

1

<code>print</code><code>(</code><code>"C:\Program Files\Windows Media Player\wmplayer.exe"</code><code>)</code>

下面是被轉義的情況:

<code>print</code><code>(</code><code>"C:\Windows\notepad.exe"</code><code>)</code>

想要正常獲得檔案路徑就得加工一下字元串。

方法一:轉義字元\\表示\:

<code>print</code><code>(</code><code>"C:\\Windows\\notepad.exe"</code><code>)</code>

這樣加工字元串比較麻煩。

方法二:字元串前加r或R聲明字元串不要轉義: 

<code>print</code><code>(r</code><code>"C:\Windows\notepad.exe"</code><code>)</code>

方法三:Python裡也可以直接使用/表示Windows的路徑。"C:\Windows\notepad.exe"可以直接寫成"C:/Windows/notepad.exe"。

如果這裡使用的是相對路徑的話,用/表示路徑的代碼在兩個平台下都可以正常運作。

本文轉自騎士救兵51CTO部落格,原文連結:http://blog.51cto.com/steed/1976904,如需轉載請自行聯系原作者