My tests are at:
src/com/xyz/tests/api_test/<Test File>
My test file calls my libraries at:
src/com/xyz/libs/api_libs/<Library File>
My library file has to open a JSON file at:
src/com/xyz/libs/api_libs/configs/<Config File>
In my library file, since its at the same parent directory as the JSON configs, I have used the following code to open the JSON.
with open('configs/sample_wlan_json'):
<Do Some action>
I tried various paths like:
.../libs/api_libs/configs/<ConfigFileName>
src/com/mist/libs/api_libs/configs/<ConfigFileName>.json
The whole path from /Users/...... but nothing seems to work.
A relative path is relative to the current working directory. Current working directory depends on how an application is started, and not where it is.
So, if you want to have a path relative to your source code, you should not rely on the current working directory, but construct the absolute path instead.
You can construct a path which is relative to your source code by using the __file__ variable, which is the path to the current py file.
Something like this should work:
configs_dir = os.path.join(__file__, '..', 'configs')
with open(os.path.join(configs_dir, 'sample_wlan.json'), 'rt') as f:
...
Related
My directory structure like below:
./outputsetting.json
./myapp/app.py
I load outputsetting.json file in app.py like below:
with open("..\outputpath.json","r") as f:
j=json.load(f)
And run in myapp directory it's ok:
python app.py
But if I run app.py in the parent directory:
python .\myapp\app.py
It raise error
FileNotFoundError: [Errno 2] No such file or directory: '..\\outputpath.json'
How can I load file from disk by the relative directory to the app.py? So I can run it from any place and needn't modify code every time.
Thanks!
When you start the script from the parent directory, the working directory for the script changes. If you want to access a file that has a specific location relative to the script itself, you can do this:
from pathlib import Path
location = Path(__file__).parent
with open(location / "../outputsetting.json","r") as f:
j=json.load(f)
Path(__file__) gets the location of the script it is executed in. The .parent thus gives you the folder the script is in, still as a Path object. And you can then navigate to the parent directory from that with location / "../etc"
Or of course in one go:
with open(Path(__file__).parent / "../outputsetting.json","r") as f:
j=json.load(f)
(Note: your code says outputpath.json, but I assume that's the same outputsetting.json)
Another solution would be to just change the working directory to be the folder the script is in - but that of course only works if all your scripts and modules are OK with that change:
from pathlib import Path
from os import chdir
chdir(Path(__file__).parent)
with open("../outputsetting.json","r") as f:
j=json.load(f)
I'd prefer constructing the absolute path as in the previous example though.
so I recently tried using playsound and the .mp3 is in the same folder as the .py, and it says it could not find the file.
I printed out the current directory and it says it's at C:\Users\me
Shouldn't this be at the same directory as where the .py script is at? This has been happening with my other python scripts where I have to explicitly give it the directory, whereas before I didn't have to and it was just where the python script was at.
Is there a setting for this?
The current directory is defined by where you execute the python file not the location of it. If you want to change the directory you can use the os module:
import os
os.chdir(PATH)
If you're looking for a file in the same directory as the executing python program:
basename = os.path.basename(__file__)
my_file_name = basename + "/myfile"
with open(my_file_name) as my_file:
...
The variable __file__ contains the full pathname of the currently executing Python program.
I just experienced a weird behaviour in Python.
I created a copy of a script.py file in a sub-folder within the folder that contains the initial script.
The script at the end exports some data into a .txt file by using:
with open('clayList.2203.txt', 'w',encoding='utf-8') as f:
for item in claysUniqueList:
f.write("%s\n" % item)
The problem is that Python writes the new file on the parent directory instead of the current one.
I checked the path with:
print(sys.path[0])
and it prints the current path correctly.
By default, relative paths are relative to the working directory, that is the directory from which is run the command that run the script.
If you want the path to be relative from the script directory, you will have to explicitly code this behaviour:
import os
filepath = os.path.join(os.path.dirname(__file__), 'clayList.2203.txt')
with open(filepath, 'w',encoding='utf-8') as f:
# ...
When you run code in Visual Studio, there are debugging options.
One of these it the directory to run from, called "Working directory".
(Right click your project and go to settings).
To run from the sub-directory you need to change this.
If you want to start in a sub directory, type that in instead, in the "working directory" shown here:
path for creating the file should be relative to the directory of execution
e.g. your pwd is parent and your script is in parent/child1/child2/script.py then path of the file to be created should be ./child1/child2/clayList.2203.txt
I have following simple script test.py in directory /Users/apps:-
import os
os.chdir("/Users/apps/update/diiferent_path")
path = os.path.dirname(os.path.abspath(__file__))
print(path)
I am getting path value as /Users/apps/update/diiferent_path because I have changed the directory. How can I get test.py path i.e. /Users/apps after changing directory.
It's impossible to do it after the chdir (unless, of course, if __file__ already contains the absolute path), because the information is lost. There is no such thing as what was the current directory when the process started stored anywhere automatically. But you can store it manually by calling os.path.abspath(__file__) before calling the chdir.
I agree with pts post that storing the path is the way to go. It best shows your intention of getting the original path, despite what modifications are done throughout the script.
For reference sake two workarounds. The path changes because the script is executed by name. The interpreter then finds the file in the current directory. The current directory changes, and thus the absolute path of both __file__ and sys.argv.
One way around that is to call the script with an absolute path. Another is to realize that the path of the script is automatically added to the PYTHONPATH, i.e. to sys.path. The following script illustrates that:
#!/usr/bin/python
import os
import sys
os.chdir("/usr/bin")
print(os.path.abspath(__file__))
print(os.path.abspath(sys.argv[0]))
print(sys.path[0])
The output:
# /tmp$ ./so24323731.py
/usr/bin/so24323731.py
/usr/bin/so24323731.py
/tmp
# /tmp$ /tmp/so24323731.py
/tmp/so24323731.py
/tmp/so24323731.py
/tmp
I am attempting to make a Python testing script module self-contained directory-wise for scalability and maintainability purposes.
I have done some research and haven't been able to find the answer i'm looking for. Basically, I would like to determine if there is a function in Python that can do something similar to cd - in shell.
I would generally like to avoid typing in full path-names, and have all the paths relative to a specified environment.
Example:
I have my main directory where my scripts are located python-scripts, I have folders for each testing environment demo, and a screenshot folder for each testing environment demo-screenshots.
If i wanted to save a screenshot to the screenshot with Python, while working in the demo directory, I would just send it to the directory below: demo-screenshots, using the path '/demo-screenshots/example.png'. The problem is that I don't understand how to move back a directory.
Thank you.
You're looking to change the working directory? The OS module in python has a lot of functions to help with this.
import os
os.chdir( path )
path being ".." to go up one directory. If you need to check where you are before/after a change of directory you can issue the getcwd() command:
mycwd = os.getcwd()
os.chdir("..")
#do stuff in parent directory
os.chdir(mycwd) # go back where you came from
path = os.path.dirname(__file__)
print(path)
will print the CWD of the file, say C:\Users\Test\Documents\CodeRevamp\Joke
path2 = os.path.dirname(path)
print(path2)
will print the Parent directory of of the file: C:\Users\Test\Documents\CodeRevamp