Let's say I have the python file ~/file_to_run.py that I want to run from jupyter notebook (~/notebooks/my_notebook.ipynb) using the magic command %run. The problem is that file_to_run.py uses a relative path for example:
open('data/file.csv') # full path ~/data/file.csv
When I run ~/file_to_run.py from ~/notebooks/my_notebook.ipynb with:
%run ../file_to_run.py
I get the following error:
FileNotFoundError: [Errno 2] No such file or directory: 'data/file.csv'
Is the any fix without modifying the python file? Thank you!
Changing the working directory could be a solution:
import os
os.chdir('../') # Change the working directory
%run file_to_run.py # Call the script from new working directory
Related
I am trying to open a .dat file by Pickle. Although the file is at the same folder as my .py file, when I run I get a FileNotFoundError.
(FYI: I am using VScode to run the file, however, it runs perfectly fine when I use Terminal)
here is my code
import pickle
websites_list = pickle.load(open("websites.dat","rb"))
print(websites_list)
This is the .py path:
/Users/lequangdang/Documents/WSC/WSC_2.0/changewebsiteGUI.py
here is the .dat path: /Users/lequangdang/Documents/WSC/WSC_2.0/websites.dat
Here is the error:
FileNotFoundError: [Errno 2] No such file or directory: 'websites.dat'
The relative path is base on work directory when using vscode, but is base on py file itself when using terminal.
For example the directory structure seems like:
WSC---WSC2.0---changewebsiteGUI.py
when you open WSC in vscode, pickle.load(open("websites.dat","rb")) will call the path WSC/websites.dat and that's why you have FileNotFoundError
one way to solve this is to set the vscode launch.json, add this line:
"cwd": "${workspaceRoot}/WSC2.0"
the other way is to use some function to get the abs path of pyfile itself:
os.path.dirname(os.path.abspath(__file__))
python: can't open file 'Test.py': [Errno 2] No such file or directory even though I have specified the working directory of the container.
CMD path
Try using full path when you try to run something.
/home/user/Test.py
I just try to create some new folders with Python's (3.7.3) os.makedirs() and os mkdir().
Apparently, it works fine because no error occurs (Win 10 Home). But as I try to find the created folder in the windows explorer it isn't there.
Trying to create it again with python I get an error:
'[WinError 183] Cannot create a file when that file already exists:'
Strange thing is, all this worked fine on my computer at work (Wind 10 too), and also on my android tablet.
I've already tried to use relative & absolute paths in makedirs / mkdir.
Ok, it's all about these few lines:
import os
# print(os.getcwd()) shows: C:\Users\Andrej\Desktop
# tried relative path..
os.makedirs('Level1/Level2/Level3')
# tried out some absolute paths like...
os.makedirs('C:/Users/Andrej/Desktop/Level1/Level2/Level3')
os.makedirs('C:\\Users\\Andrej\\Desktop\\Level1\\Level2\\Level3')
UPDATE: It works perfectly when I write makedirs command directly in the Windows powershell. The issue above only occurs when I write this code in Visual Code Studio and then start the file from the powershell by typing in: python makedirs.py...
I just had the same thing happen to me, except I was creating a folder in the AppData/Roaming directory and was using the version of Python from the Microsoft Store.
Apparently, files and directories created in AppData using that version of Python, will instead be created in:
%LocalAppData%\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache
I found what causes this problem finally!
All of the created test folders have been moved to a folder named VTROOT. This folder is created by Comodo Internet Security I use...Its "Auto-Containment" moved all folders I set up by running the code from .py-file (only then) in the PowerShell.
Disabling the auto-containment of Comodo solves the problem..Oh my..
Thank you anyways!
the "if" part will check if the file exists already and consequentially solve the ERROR: '[WinError 183] Cannot create a file when that file already exists:'
the "import sys" part will fix the issue with windows where the folder is created but not visible by the user (even with show hidden files turned on)
import sys
import os
path = 'your path'
def make_dir():
if not os.path.exists(Path):
os.makedirs(Path)
or
import sys
import os
path = 'your path'
def make_dir():
mode = 0o666 #read and write for all users and groups
# form more permission codes search for: *chmod number codes*
if not os.path.exists(Path):
os.mkdir(Path, mode)
Try adding the below import statement:
import sys
This should work.
I have to open an excel file, and I do in this way:
xl_file = pd.ExcelFile('D:\mypath\myFile.xls')
On PyCharm(Python 2.7.8) it works perfectly, but on Jupyter(Python 3), I've always this error:
FileNotFoundError: [Errno 2] No such file or directory
What could be the reason?
This might happen if you call jupyter notebook at a place other than your root directory. In this case, jupyter might not have access to the file.
Try going to D: and calling jupyter notebook and then retrying this. Another option is to get the path of your notebook using:
os.path.abspath("__file__")
and then setting a relative path to the dataset.
Edit:
Let's say you want to set a path one level above the directory that contains the notebook. Then you would do:
foo = os.path.dirname(os.path.abspath("__file__"))
relative_path = os.path.join(foo, '..')
After having changed the Jupyter start folder as suggested in this post how to change jupyter start folder? , if the files are in this folder, to load them it isnt necessary to write the path. This is enough:
xl_file = pd.ExcelFile('myFile.xls')
I'm trying to open a file in python. Simple enough. The script that I am using is the same directory as my code, so I just use
myfile = open('file.txt', 'r')
This worked fine before, but now I am getting the error 'No such file or directory' (Errno2)
Why is this happening? I've used OS to check if I am in the right directory, and it is fine. What is python doing differently now than it did 20 minutes ago, when it found the file perfectly??
Assuming the file you are trying to open/read has appropriate permissions, the behavior is defined based on how you are invoking your python program. Let's assume your code and the file.txt are in ~/Desktop
If you are in ~/Desktop and do a python code.py your code will work fine. But if you are in say your home folder - ~ and do a python ~/Desktop/code.py then the python interpreter assumes your current working directory to be ~ and will return the error:
IOError: [Errno 2] No such file or directory: 'file.txt'
since it will not find file.txt in ~
Further, in the context of the given example:
os.getcwd()
returns the absolute path of your home directory and
os.path.realpath(__file__)
returns the absolute path of your python source file
Is it possible you are typing the name wrong, eg "test.fna" versus "test.fna.txt"?