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
Related
Maybe this is to trivial question, but please assist me. How can I create folder and subfolder in it with django python. When I google I just get some information about folder structure, but it is not what I am looking for. Please share some code examples if it is possible
Many thanks.
why don't look up for how to create folders and subfolders with python using the subprocess or os ?
the ok command (linux and macos) is mkdir -p /path/you/want
You don't need much more:
import os
# creating subfolder in the directory of launched script
os.makedirs("subfolder", exist_ok=True)
# constructing full absolute path to project_folder
ROOT_FOLDER = os.path.abspath(__file__)
print(ROOT_FOLDER)
# joining root_folder and subfolder in order to create\work with files in nested folders
subfolder_abs_path = os.path.join(ROOT_FOLDER, 'subfolder')
print(subfolder_abs_path)
grass_img = pygame.image.load('grass.png').convert()
Above script is giving me: No such file or directory. I don't know if it's something with path. Because when I do it in Eclipse it doesn't give an error. I am in visual studio code, grass.png is in the same folder, or if I write the full path from C drive it's still the same error. Really frustrating. I am new. I added my project folder to the path. I really just don't understand path / python path.
Different tools may start script with different Current Working Folder (which you can check with os.getcwd()) and then it searchs your file in different place then you expect.
You could use full path to image but better you should use os.path to get folder with script
BASE = os.path.dirname(os.path.abspath(__file__))
and use os.path to create full path to image
...load( os.path.join(BASE, 'grass.png') )...
BTW:
If you will keep images in subfolder - ie. resources - then you can do
...load( os.path.join(BASE, 'resources', 'grass.png') )...
My goal is to run a python file that uses files from a folder in the same folder as the python file, but regardless of the computer's path.
The situation I have now is that I have to define paths inside my code like: C:/Users/path/to/files/etc.
The ideal situation would be if I could create a main folder (preferably a zip folder) with the python file in it, and also the necessary folders with files that the python file is using. That way I could sent the main folder to anyone and they should be able to run the python file.
I am also using the os.listdir(C:/path/to/folder) function from the os library to import a whole folder, but this also works with the computer's path. So another alternative is needed.
Does anyone know how I could do this or at least something close to this?
You can use this to get the directory in which the current Python file is using abspath and dirname:
this_dir = os.path.abspath(os.path.dirname(__file__))
And then you can construct your relative paths in a OS independent way using join:
some_image = os.path.join(this_dir, 'images', 'myimage.png')
You can do something like this
import sys, os
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
If I understand correctly, you want to use python script in another file which is located in a sub folder in the same directory. Did I get it right?
If it is you can just import it as
from <folder name> import <file name>
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
If we can directly access and manipulate files in other directories (for example, using the Python code below), when would we need to change our current working directory? What is the advantage of changing the current directory?
import os
print(os.getcwd())
f=open(os.path.join(os.getcwd(),"test_folder")+"\\testfile","w")
f.close()
print(os.getcwd())
os.makedirs("test_folder_2")
print(os.getcwd())
Output:
c:\Users\me
c:\Users\me
c:\Users\me
In the example you're not changing the working directory. You're just getting (printing) it. You do not need to change the working directory. But it's just like you are navigating your files from explorer, to keep your files organised. Sometimes it's done for the file permissions.
The current working directory is the base directory for relative paths. It is the place where you start looking for files and folders, if you don't supply an absolute path. Execute the following script from 2 different directories and examine the difference.
# a.py
import os
print "\tcwd:", os.getcwd()
print "\tpth:", os.path.abspath("a")
Now from a dos box, you get the following output:
C:\Users\user> python a.py
cwd: C:\Users\user
pth: C:\Users\user\a
C:\Users\user> cd ..
C:\Users> python user\a.py
cwd: C:\Users
pth: C:\Users\a
From a different working directory, you target different files with relative paths. It is generally a good idea to use relative paths, because otherwise a script may only work for a single user, or the installation directory of a program must be the same on all computers, which is usually not the case. You must change the working directory to target files and directories correctly with relative paths.