files地址 jupyter,__file__在Jupyter Notebook中不存在

I'm on a Jupyter Notebook server (v4.2.2) with Python 3.4.2 and

I want to use the global name __file__, because the notebook will be cloned from other users and in one section I have to run:

def __init__(self, trainingSamplesFolder='samples', maskFolder='masks'):

self.trainingSamplesFolder = self.__getAbsPath(trainingSamplesFolder)

self.maskFolder = self.__getAbsPath(maskFolder)

def __getAbsPath(self, path):

if os.path.isabs(path):

return path

else:

return os.path.join(os.path.dirname(__file__), path)

The __getAbsPath(self, path) checks if a path param is a relative or absolute path and returns the absolute version of path. So I can use the returned path safely later.

But I get the error

NameError: name '__file__' is not defined

I searched for this error online and found the "solution" that I should better use sys.argv[0], but print(sys.argv[0]) returns

/usr/local/lib/python3.4/dist-packages/ipykernel/__main__.py

But the correct notebook location should be /home/ubuntu/notebooks/.

Thanks for the reference

print(os.getcwd())

/home/ubuntu/notebooks

解决方案

If you want to get path of the directory in which your script is running, I would highly recommend using,

os.path.abspath('')

Advantages

It works from Jupyter Notebook

It work from REPL

It doesn't require Python 3.4's pathlib

Please note that one scenario where __file__ has advantage is when you are invoking python from directory A but running script in directory B. In that case above as well as most other methods will return A, not B. However for Jupyter notbook, you always get folder for .ipyn file instead of the directory from where you launched jupyter notebook.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值