Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

path problem : NameError: name '__file__' is not defined

import os.path as osp
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch_geometric.datasets import MNISTSuperpixels
import torch_geometric.transforms as T
from torch_geometric.data import DataLoader
from torch_geometric.utils import normalized_cut
from torch_geometric.nn import (NNConv, graclus, max_pool, max_pool_x, global_mean_pool)

path = osp.join(osp.dirname(osp.realpath(__file__)), '..', 'data', 'MNIST')

transform = T.Cartesian(cat=False)
train_dataset = MNISTSuperpixels(path, True, transform=transform)
test_dataset = MNISTSuperpixels(path, False, transform=transform)
train_loader = DataLoader(train_dataset, batch_size=64, shuffle=True)
test_loader = DataLoader(test_dataset, batch_size=64, shuffle=False)
d = train_dataset

I'm trying to use MNISTSuperpixels data for graph convolution, but I have some troubles using the example code. Most of scripts were using path = osp.join(osp.dirname(osp.realpath(__file__)), '..', 'data', 'MNIST') However, they gave me an error NameError: name '__file__' is not defined and I don't understand what osp.realpath(__file__) really means.

I'm using Jupyter notebook on Ubuntu, and my working directory is

print(os.getcwd())
/home/hkimlx/GDL/pytorch_geometric/examples

which is the same directory where the sample code mnist_nn_conv.py is located.

Please help me. Thanks!

like image 575
mario119 Avatar asked Jul 18 '26 09:07

mario119


2 Answers

In notebook, you need to use double quoted "__file__" as in osp.realpath("__file__") instead of osp.realpath(__file__)

Sourced from: https://queirozf.com/entries/python-working-with-paths-the-filesystem#-nameerror-name-'file'-is-not-defined

like image 69
peng Avatar answered Jul 19 '26 22:07

peng


Per the documentation

__file__ is the pathname of the file from which the module was loaded, if it was loaded from a file. The __file__ attribute may be missing for certain types of modules, such as C modules that are statically linked into the interpreter; for extension modules loaded dynamically from a shared library, it is the pathname of the shared library file.

According the answer you can't get the path of a notebook pragrammatically. Use os.getcwd() as a workaround.

like image 45
2pizza Avatar answered Jul 19 '26 23:07

2pizza



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!