Python 於 Shell 檔名遇到空白、特殊符號的處理方式

Python 於 Shell 寫入檔名,檔名遇到空白或某些特殊字元,要怎麼處理?

Python 於 Shell 檔名遇到空白、特殊符號的處理方式

Python2 和 Python3 要魚 Shell 處理檔名的特殊字元,可以使用下述 Function:

Python 2 和 Python 3 同時支援 pipes.quote()

Python3 支援

範例 (請用 Python3 執行,最後一行註解掉可使用 Python2 與 Python3 執行)

import sys
import os
import pipes # python2, python3
import shlex

fname = "abc def"

f = open(fname + ".txt", mode = "w") # 寫入檔名不需要 escape
f.write('test')
f.close()

# python2, python3
os.system("ls " + pipes.quote(fname) + ".txt")

# python3 shlex.quote()
os.system("ls " + shlex.quote(fname) + ".txt")

相關網頁

Save

作者: Tsung

對新奇的事物都很有興趣, 喜歡簡單的東西, 過簡單的生活.

發表迴響

這個網站採用 Akismet 服務減少垃圾留言。進一步了解 Akismet 如何處理網站訪客的留言資料