I'm trying to get an absolute path of a relative path string with python but it keeps printing the path twice. For example:
self.path = 'Users/abdulahmad/Desktop'
self.actual_path = os.path.abspath(self.path)
print self.actual_path
my console prints
/Users/abdulahmad/Desktop/Users/abdulahmad/Desktop
and if I change the path to:
self.path = 'Desktop'
my console prints:
/Users/abdulahmad/Desktop/Desktop
shouldn't it just print /Users/abdulahmad/Desktop in both cases?
Probably because the current working directory is /Users/abdulahmad/Desktop.
If you write for example path/to/file it means relative to current working directory and relative to /Users/abdulahmad/Desktop it would mean /Users/abdulahmad/Desktop/path/to/file.
If you read the python3 manual it actually shows an implementation of os.abspath(path) as being the same as os.path.normpath(os.path.join(os.getcwd(), path)). This can be used to get a path relative to arbitrarily provided path. (It also shows that you actually basically joins the current working directory and the supplied (relative) path)
Related
first, I will describe in short the problem I want to solve:
I have a system UNIX based, that running an automatic run that causing images creation.
those images, are saving in a directory that creating during the run and the name of the directory is unpredictable [the name is depends in so many factors and not constant.]
that directory, is created under a constant path, which is:
/usr/local/insight/results/images/toolsDB/lauto_ptest_s + str(datetime.datetime.now()).split()[
0] + /w1
So, now I got a constant form of path which is a part of my full path.
I tried to get the full path in a stupid way:
I wrote a script that open a new terminal by pressing ctrl+alt+sft+w, writing in the terminal the cd command to the constant path, and pressing tab in order to complete the full path [In the constant path there is always one directory that created so pressing tab will always get me the full path].
Theoretically, I have a full path in a terminal, how can I copy this full path and make the function return it?
this is my code:
import pyautogui
import datetime
def open_images_directory():
pyautogui.hotkey('ctrl', 'alt', 'shift', 'w')
pyautogui.write(
'cd' + ' /usr/local/insight/results/images/toolsDB/lauto_ptest_s' + str(datetime.datetime.now()).split()[
0] + '/w1/')
pyautogui.sleep(0.5)
pyautogui.hotkey('tab') # now I have a full path in terminal which I want to return by func
open_images_directory()
Not sure how you use pyautogui for that, but the proper solution would be search the directory structure with some glob patterns
Example:
from pathlib import Path
const_path = Path("const_path")
for path in [p for p in const_path.rglob("*")]:
if path.is_dir():
print(f"found directory {path}")
else:
print(f"found your image {path}")
const_path.rglob("*") searches every path recursively, (so it will contain every subdirectory), the last one will be your path you are searching for.
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'))
I'm writing some python code to generate the relative path. Situation need to be considered:
Under the same folder. I want "." or ".\", both of tham are ok for me.
Other folder. I want like ".\xxx\" and "..\xxx\xxx\"
os.path.relpath() will generate the relative path, but without .\ at the beginning and \ in the end. We can add \ in the end by using os.path.join(dirname, ""). But i can't figure out how to add ".\" at the beginning without impacting the first case when they are under the same folder and "..\xxx\xxx\".
It will give you relative path
import os
dir = os.path.dirname(__file__)
filename = os.path.join(dir,'Path')
The relpath() function will produce the ".." syntax given the appropriate base to start from (second parameter). For instance, supposing you were writing something like a script generator that produces code using relative paths, if the working directory is as the second parameter to relpath() as below indicates, and you want to reference in your code another file in your project under a directory one level up and two deep, you'll get "../blah/blah".. In the case where you want to prefix paths in the same folder, you can simply do a join with ".". That will produce a path with the correct OS specific separator.
print(os.path.relpath("/foo/bar/blah/blah", "/foo/bar/baz"))
>>> ../blah/blah
print(os.path.join('.', 'blah'))
>>> ./blah
I have Directory structure like this
projectfolder/fold1/fold2/fold3/script.py
now I'm giving script.py a path as commandline argument of a file which is there in
fold1/fold_temp/myfile.txt
So basically I want to be able to give path in this way
../../fold_temp/myfile.txt
>>python somepath/pythonfile.py -input ../../fold_temp/myfile.txt
Here problem is that I might be given full path or relative path so I should be able to decide and based on that I should be able to create absolute path.
I already have knowledge of functions related to path.
Question 1
Question 2
Reference questions are giving partial answer but I don't know how to build full path using the functions provided in them.
try os.path.abspath, it should do what you want ;)
Basically it converts any given path to an absolute path you can work with, so you do not need to distinguish between relative and absolute paths, just normalize any of them with this function.
Example:
from os.path import abspath
filename = abspath('../../fold_temp/myfile.txt')
print(filename)
It will output the absolute path to your file.
EDIT:
If you are using Python 3.4 or newer you may also use the resolve() method of pathlib.Path. Be aware that this will return a Path object and not a string. If you need a string you can still use str() to convert it to a string.
Example:
from pathlib import Path
filename = Path('../../fold_temp/myfile.txt').resolve()
print(filename)
A practical example:
sys.argv[0] gives you the name of the current script
os.path.dirname() gives you the relative directory name
thus, the next line, gives you the absolute working directory of the current executing file.
cwd = os.path.abspath(os.path.dirname(sys.argv[0]))
Personally, I always use this instead of os.getcwd() since it gives me the script absolute path, independently of the directory from where the script was called.
For Python3, you can use pathlib's resolve functionality to resolve symlinks and .. components.
You need to have a Path object however it is very simple to do convert between str and Path.
I recommend for anyone using Python3 to drop os.path and its messy long function names and stick to pathlib Path objects.
import os
dir = os.path.dirname(__file__)
path = raw_input()
if os.path.isabs(path):
print "input path is absolute"
else:
path = os.path.join(dir, path)
print "absolute path is %s" % path
Use os.path.isabs to judge if input path is absolute or relative, if it is relative, then use os.path.join to convert it to absolute
Let's consider the below code:
fp=open('PR1.txt','r')
ch=fp.readlines()
print "%s" % (' '.join(ch))
print "\n"
fp.close()
Above code gives an error:
IOError: [Errno 2] No such file or directory: 'PR1.txt'
But when i am provididng its full location i.e;
fp=open('D:/PR1.txt','r')
then it is working properly...
IS it necessary to provide full location of file or there is some other way too?
No, it is not necessary, but you need to be certain you are running your script with the right working directory. Your script working directory is evidently not D:/.
In practice, it is better to only use relative paths if you are in full control of the working directory. You can get the current working directory with os.getcwd() and set it with os.chdir() but using absolute paths is usually better.
For paths relative to the current module or script, use the __file__ global to produce a directory name:
import os.path
here = os.path.dirname(os.path.absolute(__file__))
then use os.path.join() to make relative paths absolute in reference to here.