Python directory file go wrong - python

I am having a silly problem with reading a file in python.
I have a folder 'a' that contains my test.py and file test.json for reading.
My test.py looks like this:
config_path = 'test.json'
with open(config_path) as config_buffer:
config = json.loads(config_buffer.read())
When I go outside the directory structure of folder 'a' and I run the command:
python a\test.py
And the console returns this error:
FileNotFoundError: No such file or directory: 'test.json'
I try using the absolute file path using pathlib:
config_path = Path('end2end.json').absolute()
with open(config_path) as config_buffer:
config = json.loads(config_buffer.read())
But it still returns this error to me:
FileNotFoundError: No such file or directory: 'D:\\test.json'
Can anyone help me to get exactly the right directory file?

If you want to call your python script from any folder and let it access its local files without specifying paths, you can change the directory in the begining:
import os
os.chdir(os.path.dirname(os.path.realpath(__file__)))
config_path = 'test.json'
...

The Problem is that you should place the test.json file in the current working directory.
i.e)For Example, The python file is located in C:\users\Desktop\Code\test.py then you should copy the file into C:\users\Desktop\Code\
(OR)
You should give the path of the file in with open($PATH TO JSON FILE) as config_buffer

Related

opening a .txt file

first, i'd like to mention that im using python via visual studio. not sure if this information will
be relevant but this is my first time using file input so i'm not sure
basically, i have a .txt file located in the same location as my .py file. however, when i go to access it, i get an error 'FileNotFoundError: [Errno 2] No such file or directory'
is there a way to make it work or a different IDE i should use?
I tried reading a .txt file from the same location as my .py file. however, i keep getting the error 'FileNotFoundError: [Errno 2] No such file or directory'
Take into account that the script might not be running from the same path where your python script is and most probably your are not specifying the exact path of the file.
If your file is located in the same directory where your python sript is you can use the pathlib library this way to get your script to work:
import pathlib
# Some custom code
# find your current script path
current_script_path = pathlib.Path(__file__).parent
my_file_name = "my_file_name.txt"
# Specify the file path relative to your script's path
my_file_path = current_script_path / my_file_name
with open(my_file_path, "r+") as f:
print(f.read())

FileNotFoundError in Python Visul Studio

I get this when I try to run my python project code
with open("config.json", "r") as f:
Exception raised:
FileNotFoundError: [Errno 2] No such file or directory: 'config.json'
what is a solution for this?
here is a screenshot of the code and everything.
the file config.jason needs to be in your current working directory to be found by open if you do not use a full path. Your cwd is probably where you launched python. To check do
import os
print(os.getcwd())
Your easiest solution is probably to use a full path name for the file.
As shown in the screenshot of the IDE, you should exactly point out where the .json file. Now the json file and python code are not located in the same folder.
FYI, there are two types of path, absolute path and relative path. Please see https://www.kite.com/python/answers/how-to-find-the-absolute-and-relative-path-of-a-file-in-pythonhttps://www.kite.com/python/answers/how-to-find-the-absolute-and-relative-path-of-a-file-in-python
with open("/file program/config.json", "r") as f
content = f.read()
# do something
Or, just move out the config.json file to the folder, which the python code is located.

python - error occurs on relative path but not absolute path in macOS

I'm having a strange issue. I'm just trying to do a basic show directory contents for relative path.
Created a test directory on the desktop
test directory contents
test.py
test1 -- folder
sample.txt
contents of test.py
import os
dataDir = "test1"
for file in os.listdir("/Users/username/Desktop/test"):
print(file)
Summary - absolute path
works - in visual studio code
works - macOS terminal python3 /Users/username/Desktop/test/test.py
however when use the variable I get an error:
contents of test.py
import os
dataDir = "test1"
for file in os.listdir(dataDir):
print(file)
Summary - relative path
works - in visual studio code
ERROR - macOS terminal python3 /Users/username/Desktop/test/test.py
Traceback (most recent call last):
File "/Users/username/Desktop/test/test.py", line 4, in
for file in os.listdir(dataDir):
FileNotFoundError: [Errno 2] No such file or directory: 'test1'
I all depends on what folder you are in when you launch the code.
Let's say your .py file is in folder1/folder2/file.py and your test1 folder is folder1/folder2/test1/.... You open a terminal in the folder1 and launch python3 /folder2/file.py. The program is going to check for files in folder1/test1/.
Try navigating to the actual file folder, that should work. If you want to use it wherever you launch the code you will have to do some checks on the current directory and manually point the code to the wanted path.
The following solution is inspired by that answer
A simple way to solve your problem is to create the absolute path. (I recommend using that always when you're working with different directories and files)
First of all, you need to care about your actual working directory. While using VS Code your working directory is in your desired directory (/Users/username/Desktop/test/).
But if you use the command line your actual working directory may change, depending where you're calling the script from.
To get the path where script is actually located, you can use the python variable __file__. __file__ is the full path to the directory where your script is located.
To use your script correctly and being able to call it using both ways, the following implementation can help you:
import os
dataDir = "test1"
# absolute path to the directory where your script is in
scriptDir = os.path.dirname(__file__)
# combining the path of your script and the 'searching' directory
absolutePath = os.path.join(scriptDir, dataDir)
for file in os.listdir(absolutePath):
print(file)

Reading file from one up directory in python2.7

I am trying to read file in a python script from one up level.
My file structure is as below:
code
- scripts
-myscript.py
- .env
In .env I have my configs.
And I am trying to read this file in myscript.py
I did the below to read it:
envfile = open("../.env", "r")
Now when I run this python script from the scripts directory it works fine
This works good:
cd /var/www/html/code/scripts
python myscript.py
But if I do:
cd
python /var/www/html/code/scripts/myscript.py
Doesn't work and gives IOError: [Errno 2] No such file or directory: '../.env'
How can I make it to run if I pass the absolute or relative path in terminal?
You can use pathlib2:
pathlib2 is the version for python 2.7
pathlib Module: Taming the File System
from pathlib import Path
path = Path(__file__).resolve().parents[1].joinpath(".env")
envfile = open(path)
import os
p = os.path.realpath(__file__)
envfile = open('/'.join(p.split('/')[:-1])+'/../.env')
also works

Call a file in another folder in Eclipse for Python project

I have a small enough Python project in Eclipse Neon and keep getting the same error and can't find proper documentation on how to solve. In my main I need to call a file that is located in another folder. The error I receive is IOError: [Errno 2] No such file or directory:
I have an empty init.py file in the folder (XML_TXT) that I'm trying to use.
It looks like Groovy is importing okay, or else you would get an ImportError. An IOError indicates that it can't find "test.txt". Does that file exist?
It will work if the file path is relative to where you are running the script from. So for example if test.txt is in a folder
Groovy("folder_name/test.txt")
You can also go up in the directory structure if you need to, for example
Groovy("../folder_name/test.txt")
Or, if you want to be able to run the file from anywhere, you can have python work out the absolute path of the file for you.
import os
filename = os.path.join(os.path.dirname(__file__), 'folder_name/test.txt')
u = Groovy(filename)

Categories