getting correct path of a folder in python - python

I have a directory structure as below
/home/damon/dev/python/misc/path/
/project/mycode.py
/app/templates/
I need to get the absolute path of the templates folder from mycode.py
I tried to write mycode.py as
import os
if __name__=='__main__':
PRJ_FLDR=os.path.dirname(os.path.abspath(__file__))
print 'PRJ_FLDR=',PRJ_FLDR
apptemplates = os.path.join(PRJ_FLDR,'../app/templates')
print 'apptemplates=',apptemplates
I expected the apptemplates to be
/home/damon/dev/python/misc/path/app/templates
but I am getting
/home/damon/dev/python/misc/path/project/../app/templates
How do I get the correct path?

That path is correct, try it. But if you want to remove the redundant 'project/../' section for clarity, use os.path.normpath
os.path.normpath(path)
Normalize a pathname. This collapses redundant separators and up-level references so that A//B, A/B/, A/./B and A/foo/../B all become A/B.
http://docs.python.org/2/library/os.path.html#os.path.normpath

Is this what you want?
import os
if __name__=='__main__':
PRJ_FLDR=os.path.dirname(os.path.abspath(__file__))
print 'PRJ_FLDR=',PRJ_FLDR
apptemplates = os.path.abspath(os.path.join(PRJ_FLDR, '../app/templates'))
print 'apptemplates=',apptemplates
Considering the comments, I made the proper edit.

I tried this ,and it seems to work
parentpath=os.path.abspath(os.path.join(os.path.dirname(__file__),".."))
apptemplates=os.path.join(parentpath,'app/templates')

This works:
apptemplates = os.path.join(os.path.split(PRJ_FLDR)[0], "app/templates")

Related

os.join.path does change directory

Hello I have a piece of code where I want to join a path with a picture name which I am getting from an excel file. The thing is that my code changes my path string.
src=os.path.join('C:\\Users\\ekrem\\Desktop\\Distributions\\16-17',ws.cell(row=cell.row,column=2).value)
print('src=',src)
so here my src variable should be something like this:
C:\Users\ekrem\Desktop\Distributions\16-17\26231043_1686575684735993_7548330554586169888_n.jpg
but as you see I printed the src variable and I got this
src= C:\Users\ekrem\Desktop\16-17\26231043_1686575684735993_7548330554586169888_n.jpg
here the distribution folder is missing, have you any idea why?
Thank you in advance
In this case assuming the end piece is always a single filename it might be easier to do this with f-strings. That way there is no path weirdness that happens something like this should work (Assuming you're on python 3.6+, if you aren't then do this instead):
src = f'C:\\Users\\ekrem\\Desktop\\Distributions\\16-17\\{ws.cell(row=cell.row,column=2).value}'
print(f'{source=}') # Print source with label
P.S I would recommend switching the C:\\Users\\<name> with %USERPROFILE% (so %USERPROFILE%\\Desktop\\Distributions\\16-17\\), that way if you change accounts or hard-drives this still works.
Then just do validation with:
if os.path.exists(src):
# Do stuff
else:
raise FileNotFoundError(f"{src} file could not be found")

Python Convert Windows File path in a variable

Given is a variable that contains a windows file path. I have to then go and read this file. The problem here is that the path contains escape characters, and I can't seem to get rid of it. I checked os.path and pathlib, but all expect the correct text formatting already, which I can't seem to construct.
For example this. Please note that fPath is given, so I cant prefix it with r for a rawpath.
#this is given, I cant rawpath it with r
fPath = "P:\python\t\temp.txt"
file = open(fPath, "r")
for line in file:
print (line)
How can I turn fPath via some function or method from:
"P:\python\t\temp.txt"
to
"P:/python/t/temp.txt"
I've tried also tried .replace("\","/"), which doesnt work.
I'm using Python 3.7 for this.
You can use os.path.abspath() to convert it:
print(os.path.abspath("P:\python\t\temp.txt"))
>>> P:/python/t/temp.txt
See the documentation of os.path here.
I've solved it.
The issues lies with the python interpreter. \t and all the others don't exist as such data, but are interpretations of nonprint characters.
So I got a bit lucky and someone else already faced the same problem and solved it with a hard brute-force method:
http://code.activestate.com/recipes/65211/
I just had to find it.
After that I have a raw string without escaped characters, and just need to run the simple replace() on it to get a workable path.
You can use Path function from pathlib library.
from pathlib import Path
docs_folder = Path("some_folder/some_folder/")
text_file = docs_folder / "some_file.txt"
f = open(text_file)
if you would like to do replace then do
replace("\\","/")
When using python version >= 3.4, the class Path from module pathlib offers a function called as_posix, which will sort of convert a path to *nix style path. For example, if you were to build Path object via p = pathlib.Path('C:\\Windows\\SysWOW64\\regedit.exe'), asking it for p.as_posix() it would yield C:/Windows/SysWOW64/regedit.exe. So to obtain a complete *nix style path, you'd need to convert the drive letter manually.
I came across similar problem with Windows file paths. This is what is working for me:
import os
file = input(str().split('\\')
file = '/'.join(file)
This gave me the input from this:
"D:\test.txt"
to this:
"D:/test.txt"
Basically when trying to work with the Windows path, python tends to replace '' to '\'. It goes for every backslash. When working with filepaths, you won't have double slashes since those are splitting folder names.
This way you can list all folders by order by splitting '\' and then rejoining them by .join function with frontslash.
Hopefully this helps!

list of jpeg files in nested subdirectories

I use the following python code to get list of jpg files in nested subdirectories which are in parent directory.
import glob2,os
all_header_files = glob2.glob(os.path.join('Path/to/parent/directory','/**/*.jpg'))
However, I get nothing but when I cd into the parent directory and I use the following python code then I get the list of jpeg files.
import glob2
all_header_files = glob2.glob('./**/*.jpg')
How can I get the result with the absolute path?(first version)
You have an extra slash.
The os.path.join will insert the filepath separators for you, so you should think of it as this to get the correct directory
join('Path/to/parent directory' , '**/*.jpg')
Even more accurately,
parent = os.path.join('Path', 'to', 'parent directory')
os.path.join(parent, '**/*.jpg')
If you are trying to use your Home directory, see os.path.expanduser
In [10]: import os, glob
In [11]: glob.glob(os.path.join('~', 'Downloads', "**/*.sh"))
Out[11]: []
In [12]: glob.glob(os.path.expanduser(os.path.join('~', 'Downloads', "**/*.sh")))
Out[12]:
['/Users/name/Downloads/dir/script.sh']
You should not join with the trailing slash as you'll end up with the root. You can debug by printing out the resulting path before passing it to glob.
Try to change your code like this (note the dot):
import glob2,os
all_header_files = glob2.glob(os.path.join('Path/to/parent directory','./**/*.jpg'))
os.path.join() joins paths in an intelligent way.
os.path.join('Path/to/anything','/**/*.jpg'))
resolves to '/**/*.jpg' since '/**/*.jpg' is any path, ever.
Change the '/**/*.jpg' to '**/*.jpg' and it should work.
In cases like this, I recommend to always try out the result of a certain function within the python command line. At least, this is how I found out the issue here.
The problem with the code you have posted lies in the use of os.path.join.
In the documentation it says for os.path.join(path, *paths):
If a component is an absolute path, all previous components are thrown away and joining continues from the absolute path component.
In your case, the component /**/*.jpg is an absolute path, as it starts with a /. Consequently your initial input /Path/to/parent directory is being truncated by the call to the join function. (https://docs.python.org/3.5/library/os.path.html#os.path.join)
I have locally tested the joining part with python3 and for me it is the case, that using os.path.join(any_path, "/**/*.pdf") returns the string '/**/*.pdf'.
The fix for this error is:
import glob2,os
all_header_files = glob2.glob(os.path.join('Path/to/parent directory','**/*.jpg'))
This returns the path 'Path/to/parent directory/**/*.jpg'

Remove a string (filename) from a bigger string (the whole path)

Say that I have this string "D:\Users\Zache\Downloads\example.obj" and I want to copy another file to the same directory as example.obj. How do I do this in a way that´s not hardcoded?
"example" can also be something else (user input). I'm using filedialog2 to get the big string.
This is for an exporter with a basic GUI.
os.path.dirname() gives you the directory portion of a given filename:
>>> import os.path
>>> os.path.dirname(r"D:\Users\Zache\Downloads\example.obj")
'D:\\Users\\Zache\\Downloads'
You can solve it with str.split but this should be solved with os.path.split

python os.path.realpath not working properly

I have following code:
os.chdir(os.path.dirname(os.path.realpath(__file__)) + "/../test")
path.append(os.getcwd())
os.chdir(os.path.dirname(os.path.realpath(__file__)))
Which should add /../test to python path, and it does so, and it all runs smoothly afterwards on eclipse using PyDev.
But when I lunch same app from console second os.chdir does something wrong, actually the wrong thing is in os.path.realpath(__file__) cus it returns ../test/myFile.py in stead of ../originalFolder/myFile.py. Of course I can fix this by using fixed os.chdir("../originalFolder") but that seems a bit wrong to me, but this works on both, eclipse and console.
P.S. I'm using os.getcwd() actually because I want to make sure there isn't such folder already added, otherwise I wouldn't have to switch dir's at all
So is there anything wrong with my approach or I have messed something up? or what? :)
Thanks in advance! :)
Take a look what is value of __file__. It doesn't contain absolute path to your script, it's a value from command line, so it may be something like "./myFile.py" or "myFile.py". Also, realpath() doesn't make path absolute, so realpath("myFile.py") called in different directory will still return "myFile.py".
I think you should do ssomething like this:
import os.path
script_dir = os.path.dirname(os.path.abspath(__file__))
target_dir = os.path.join(script_dir, '..', 'test')
print(os.getcwd())
os.chdir(target_dir)
print(os.getcwd())
os.chdir(script_dir)
print(os.getcwd())
On my computer (Windows) I have result like that:
e:\parser>c:\Python27\python.exe .\rp.py
e:\parser
e:\test
e:\parser
e:\parser>c:\Python27\python.exe ..\parser\rp.py
e:\parser
e:\test
e:\parser
Note: If you care for compatibility (you don't like strange path errors) you should use os.path.join() whenever you combine paths.
Note: I know my solution is dead simple (remember absolute path), but sometimes simplest solutions are best.

Categories