自学内容网 自学内容网

Python笔记之识别到当前python脚本所在的目录,而不是执行python命令的目录

Python笔记之识别到当前python脚本所在的目录,而不是执行python命令的目录

在这里插入图片描述

code review!

1.题解

要在Python脚本中识别到脚本所在的目录,可以使用os模块中的__file__属性。以下是一个示例:

import os

# 获取当前脚本所在的目录
script_dir = os.path.dirname(os.path.abspath(__file__))

print("当前脚本所在的目录:", script_dir)

这段代码使用os.path.abspath(__file__)来获取脚本的绝对路径,然后用os.path.dirname()获取目录路径。这样可以确保得到的是脚本文件所在的目录,而不是执行命令的目录。

2.在脚本所在的目录后面拼接下一层目录

要在脚本所在的目录后面拼接下一层目录,可以使用os.path.join()。下面是一个示例:

import os

# 获取当前脚本所在的目录
script_dir = os.path.dirname(os.path.abspath(__file__))

# 拼接下一层目录的路径
next_layer_dir = os.path.join(script_dir, '下一层目录名')

print("下一层目录的路径:", next_layer_dir)

'下一层目录名'替换为要拼接的目录名即可。这样可以确保路径的拼接是跨平台的。


原文地址:https://blog.csdn.net/weixin_43297891/article/details/142749150

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!