用于在Spyder中将工作目录设置为源文件位置的Python命令
我想要一行python代码,将工作目录设置为代码所在的文件夹。我使用spyder IDE编写和运行python代码用于在Spyder中将工作目录设置为源文件位置的Python命令,python,spyder,Python,Spyder,我想要一行python代码,将工作目录设置为代码所在的文件夹。我使用spyder IDE编写和运行python代码 旁注:这个问题非常类似于这是我在Jupyter中开发命令行时遇到的一个常见问题 您可以尝试以下操作以查找脚本的执行位置: import os from pathlib import Path def myPath(): ''' return the current working directory in both interpeters and when exe
旁注:这个问题非常类似于这是我在Jupyter中开发命令行时遇到的一个常见问题 您可以尝试以下操作以查找脚本的执行位置:
import os
from pathlib import Path
def myPath():
'''
return the current working directory in both interpeters and when exectued on the commandline
'''
try:
# path of this file when executed
wd = os.path.dirname(os.path.abspath(__file__))
except NameError as e:
print('this script is running in an interpreter')
# if not found
wd = Path().resolve()
return(wd)