os获取当前目录、上级目录、上上级目录…
import os
# 获取当前目录
print(os.getcwd())
print(os.path.abspath(os.path.dirname(__file__)))
# 获取上级目录
print(os.path.abspath(os.path.dirname(os.path.dirname(__file__))))
print(os.path.abspath(os.path.dirname(os.getcwd())))
print(os.path.abspath(os.path.join(os.getcwd(), "..")))
# 获取上上级目录
print(os.path.abspath(os.path.join(os.getcwd(), "../..")))
# 获取上上上级目录
print(os.path.abspath(os.path.join(os.getcwd(), "../../..")))
# 调用上级目录下另一个文件夹内的文件
up_dir_path = os.path.abspath(os.path.join(os.getcwd(), ".."))
demo_path = os.path.join(up_dir_path, "utils/demo.txt")
print(demo_path)
with open(demo_path, "r", encoding="utf-8") as file:
print(file.read())
输出
E:\PyCharmCodeFile\BasicStandardRec\text_similar
E:\PyCharmCodeFile\BasicStandardRec\text_similar
E:\PyCharmCodeFile\BasicStandardRec
E:\PyCharmCodeFile\BasicStandardRec
E:\PyCharmCodeFile\BasicStandardRec
E:\PyCharmCodeFile
E:\
E:\PyCharmCodeFile\BasicStandardRec\utils/demo.txt
asaf
关于os.path.join()
os.path.join()函数:连接两个或更多的路径名组件
1.如果各组件名首字母不包含’/’,则函数会自动加上
2.从第一个以”/”开头的参数开始拼接,之前的参数全部丢弃;当有多个时,从最后一个开始
3.如果最后一个组件为空,则生成的路径以一个’/’分隔符结尾