在Python 3.4+中,您可以使用pathlib模块获取父目录。例如,
from pathlib import Path print(Path('/home/username').parent) This will give the output: /home
在旧版本中,您可以在路径上调用os.path.join并使用“ ..”(代表父目录),然后使用os.path.abspath找到其绝对路径。
import os print(os.path.abspath(os.path.join('/home/username', '..'))) This will give the output: /home