windows 中路徑使用反斜線,linux下路徑使用’/’, windows下的路徑在linux下是不能被識別的。
path = os.path.split(os.path.realpath(file))[0] + r’\cmds’, 這樣的路徑不會被linux所識別
解決方案
- 使用os.path.join
path = os.path.join(os.path.split(os.path.realpath(__file__))[0], 'cmds')
- 使用os.sep, python會根據不同的系統自動選擇合適的路徑分隔
path = os.path.split(os.path.realpath(__file__))[0] + os.sep + 'cmds'
- 可以將所有的路徑都使用正斜線:’/’, 在windows和linux都有效
path = path.replace('\\', '/')
- 使用最新的pathlib模塊
import pathlib pathlib.Path('C:\dir', 'cmds') # WindowsPath('C:/dir/cmds') # 或者 pathlib.Path('C:\dir')/'cmds' # WindowsPath('C:/dir/cmds')