Python - How to specify a relative path by jumping a subdirectory? - python

I'm in one location i.e. 'c:/program files/java' and I want to jump two levels down without having to specify the subfolders i.e. I want to move to 'c:/program files/java/7.0/jre/bin' without specifying '/7.0/'.
A snippet I'm using is:
import os
os.chdir('c://program files//java')
os.getcwd()
'c:/program files/java'
Now I want to use os.chdir() to move to '/7.0/jre' so os.getcwd() is 'c://program files//java/7.0/jre'
without having to specify '7.0' i.e. os.chdir('.\**7.0**\jre')
Does anyone have any suggestions?

You can use glob.glob:
import glob
import os
os.chdir('c:/program files/java')
os.chdir(glob.glob('*/jre')[0])
Above code will change working directory to c:/program files/java/*/jre.
In case there are multiple java directory, and you want to go to specific directory (for example, to the newest version directory), you should manipulate the return value of glob.glob().

Related

How to create a Path from a variable?

I have been running some script in VBA which I like to convert in Python. In VBA I use variables to identify the path from which the raw data are collected so that the same script can be used in any machine. In order to do do so in VBA I identify the path by using the using the following string:
"C:\Users\" & Environ$("username") & "\Data"
Is there a way I can identify in the same way the path in Python?
Use pathlib from the Python Standard Library.
import pathlib
print(pathlib.Path.home() / 'Data')
In older versions of Python (before pathlib) you could use os.path.
import os.path
print(os.path.join(os.path.expanduser('~'), 'Data'))
Some additional info: if you want to reference the path where your script is, you can do that too. You just have to know that __file__ contains the full path to your script.
import pathlib
# full path to the script
print(pathlib.Path(__file__))
# full path to the scripts folder
print(pathlib.Path(__file__).parent)
# full path to the subfolder 'subfolder' in the scripts folder
print(pathlib.Path(__file__).parent / 'subfolder')
# full path to a file in the subfolder
print(pathlib.Path(__file__).parent / 'subfolder' / 'datafile.csv')
Just to add to Matthias answer: in case you are looking to use python to "find" a path to the save a file you should keep in mind that despite printing the correct path, Python won't recognize the path unless, after identify the correct Path, you convert it to a string
i.e.: suppose you set your path as a variable
path = pathlib.Path(__file__).parent / 'subfolder' / 'datafile.csv'
then you need to covert path as a string to be used to open/save a file
path1 = str(path)
then you can use path1 to open/save a file

python import with absolute path

I have the following folder structure and want to find a good way to import python modules.
project1/test/benchmark/benchmark_project1.py
#in benchmark_project1.py
from project1.test.benchmark import *
My question is how to get rid of project1, since it might be renamed to "project2" or something else. I want to use import with absolute path, but don't know a good way to achieve that.
You can use os.chdir() to change your directory before the import statement, and then to change it back afterward. This will allow you to specify the precise file to import. You can use os.listdir() to get the list of all files in the directory, and then simply index them. Using a loop will get all the modules in the folder, or providing the right index according to some pattern will give you a specific one. The glob module allows you to select files using regex.
import os
cwd = os.getcwd()
new_dir = 'project1/test/benchmark/'
list_dir = os.listdir(new_dir) # Find all matching
os.chdir(new_dir)
for i in range(len(list_dir)): # Import all of them (or index them in some way)
module = list_dir[i][0:-3] # Filter off the '.py' file extension
from module import *
os.chdir(cwd)
Alternatively, you can add the location to your path instead of changing directories. Take a look at this question for some additional resources.

Add and change relative directory to an existed path (python script)

There is a default path in a function:
def function(directory):
path = ('/a/b/c/d/e/f/g')
newdirectory = (This is the part I am asking)
I call this function:
from xxx import function:
p('../../x/y')
I need to get a new directory 'newdirectory', which is supposed to be 'a/b/c/d/e/x/y', in order to proceed to the next step, but I don't know how to add the relative directory to an absolute directory and generate a new absolute directory
Use os.path.join() to join the two path strings together, and os.path.abspath() to resolve the relative parts into one absolute path.
import os
print os.path.abspath(os.path.join('/a/b/c/d/e/f/g', '../../x/y'))

How do go into a directory without being given its full path in python 2?

I am currently trying to go into a folder and call a python 2 script, but I cannot get any answer to go into a folder without using its full path. As example in DOS I would normally type this:
C:\unknownpath\> cd otherpath
C:\unknownpath\otherpath\>
Thanks for any help.
Try this:
import os
os.chdir('otherpath')
This at least matches your DOS example, and will change your working directory to otherpath relative to the directory the command is run from. For example if you are in /home/myusername/, then this will take you to /home/myusername/otherpath/. You can also use . for the current directory or .. to move back one directory. So if you are in /home/myusername/Desktop/, os.chdir('..') would change the working directory to /home/myusername/ and os.chdir('../Documents/ would change you to /home/myusername/Documents/, etc.
Forgive my use of Unix-style paths, but you should be able to easily translate these commands to Windows paths if that is the platform you are on. I don't want to attempt to use Windows paths in my examples because I won't be able to test their efficacy.
os.chdir works on relative path.
>>> os.getcwd()
'C:\\Users\\sba001\\PycharmProjects'
>>> os.listdir('.')
['untitled', 'untitled1', 'untitled2', 'untitled3', 'untitled4', 'untitled5']
>>> os.chdir('untitled')
>>> os.getcwd()
'C:\\Users\\sba001\\PycharmProjects\\untitled'

How to set current working directory in python in a automatic way

How can I set the current path of my python file "myproject.py" to the file itself?
I do not want something like this:
path = "the path of myproject.py"
In mathematica I can set:
SetDirectory[NotebookDirectory[]]
The advantage with the code in Mathematica is that if I change the path of my Mathematica file, for example if I give it to someone else or I put it in another folder, I do not need to do anything extra. Each time Mathematica automatically set the directory to the current folder.
I want something similar to this in Python.
The right solution is not to change the current working directory, but to get the full path to the directory containing your script or module then use os.path.join to build your files path:
import os
ROOT_PATH = os.path.dirname(os.path.abspath(__file__))
# then:
myfile_path = os.path.join(ROOT_PATH, "myfile.txt")
This is safer than messing with current working directory (hint : what would happen if another module changes the current working directory after you did but before you access your files ?)
I want to set the directory in which the python file is, as working directory
There are two step:
Find out path to the python file
Set its parent directory as the working directory
The 2nd is simple:
import os
os.chdir(module_dir) # set working directory
The 1st might be complex if you want to support a general case (python file that is run as a script directly, python file that is imported in another module, python file that is symlinked, etc). Here's one possible solution:
import inspect
import os
module_path = inspect.getfile(inspect.currentframe())
module_dir = os.path.realpath(os.path.dirname(module_path))
Use the os.getcwd() function from the built in os module also there's os.getcwdu() which returns a unicode object of the current working directory
Example usage:
import os
path = os.getcwd()
print path
#C:\Users\KDawG\Desktop\Python

Categories