#๐ FileNotFoundError: [Errno 2] No such file or directory but file exists
40 messages ยท Page 1 of 1 (latest)
@flint ermine
Remember to:
- Ask your Python question, not if you can ask or if there's an expert who can help.
- Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
- Explain what you expect to happen and what actually happens.
:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.
Try os.path.join of your base directory
Something like this:
import os
drive = "C:" # (this would be different for linux or mac)
base_dir = "Users"
username = "yourname"
project_folder = "projectname"
filename = "yourfilename.txt"
# Join all parts to create the full path
file_path = os.path.join(drive, base_dir, username, project_folder, filename)
# Open the file using the constructed path
with open(file_path, 'r') as file:
content = file.read()
print(content)```
Is the file you want located in the same directory as the Python file you're running?
It is yes
from pathlib import Path
myfile = Path(__file__).parent / "filename.json"
with open(myfile) as file:
...
__file__ gives the absolute path to the current Python module. pathlib.Path.parent can then give the directory containing that file.
The rest joins your filename onto that directory, giving the correct absolute path to the file
Just the name of the file in question. ๐
__file__ is a special variable, so that part is literal.
Ah okay, glad to know that
Why the original code might have had an issue is because a plain filename is joined relative to the current working directory, which might be a different one from the directory containing the source code.
Things get wonky that way. Building an absolute path this way is much more consistent.
You probably want to use an IDE to write your code. It'll give you nice syntax highlighting and generally make programming much more comfortable
Most people use VsCode or Pycharm
did this not work which is why tried adding that C: ?
I'm running this through Python
Through my command terminal
And what I mean by it didn't work is that I tried opening the file again after running it and it gave me the same message
I tried adding a C:
so u opening up a new terminal and doing py main.py ?
Yup
Oh I think it might be working?
I'm going to test it one second
It is working
whew
This help channel has been closed. Feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.
