In Python when I print directory path constructed with os.join I get something like this :
rep/rep2/../rep1
Is there a way to get only this :
rep/rep1
Yes, os.path.normpath() collapses redundant separators and up-references.
os.path.realpath() converts the path to a canonical path, which includes eliminating '..' components, but it also eliminates symlinks.
See https://docs.python.org/2/library/os.path.html.
Use os.path.relpath:
>>> import os
>>> os.path.relpath("rep/rep2/../rep1", start="")
'rep/rep1'
Or os.path.normpath:
>>> import os
>>> os.path.normpath("rep/rep2/../rep1")
'rep/rep1'
Related
I'm looking for the cleanest way to add a path separator to the beginning of a relative path if it's not already there.
So for example my/path should result in /my/path/.
The way I do it now is the following:
import os
os.sep+'my/path'
This approach works but when a non relative path is passed it will also add the separator which is something I want to avoid.
Suggestions?
Try os.path.join with the root directory as its first argument.
>>> import os
>>> os.path.join('/', '/tmp')
/tmp
>>> os.path.join('/', 'tmp')
/tmp
I'm working with different path functions like os.path.join, os.path.normalize or os.walk but not getting the desired paths. I want to get the '/' separator in paths. Can I change the default separator which is used by os.sep or is their a way to tell path functions, which sep/altsep to use?
My code is like this:
dataset_dir = './dataset'
for paths,subdir,files in os.walk(dataset_dir):
for file in files:
print(os.path.join(paths, file))
#here i want a path like './dataset/abc_dir/xyz.jpg
#but I'm getting ./dataset\abc_dir\xyz.jpg
You can use the modules posixpath respectivelly ntpath for specific path formats.
>>> import posixpath
>>> posixpath.join('path', 'file')
'path/file'
>>> import ntpath
>>> ntpath.join('path', 'file')
'path\\file'
You can also take a look at the PurePaths provided by pathlib. Since they don't actually access the filesystem you can use them independent of the underlying system.
>>> from pathlib import PurePosixPath, PureWindowsPath
>>> print(PureWindowsPath('path', 'file'))
hello\world
>>> print(PurePosixPath('path', 'file'))
hello/world
I have a directory I'd like to print out with a trailing slash: my_path = pathlib.Path('abc/def')
Is there a nicer way of doing this than os.path.join(str(my_path), '')?
No, you didn't miss anything. By design, pathlib strips trailing slashes, and provides no way to display paths with trailing slashes. This has annoyed several people, as mentioned in the bug tracker: pathlib strips trailing slash.
A compact way to add slashes in Python 3.6 is to use an f-string, eg f'{some_path}/' or f'{some_path}{os.sep}' if you want to be OS-agnostic.
from pathlib import Path
import os
some_path = '/etc'
p = Path(some_path)
print(f'{p}/')
print(f'{p}{os.sep}')
output
/etc/
/etc/
Another option is to add a dummy component and slice it off the resulting string:
print(str(p/'#')[:-1])
To add a trailing slash of the path's flavour using just pathlib you could do:
>>> from pathlib import Path
>>> my_path = Path("abc/def")
>>> str(my_path / "_")[:-1] # add a dummy "_" component, then strip it
'abc/def/'
Looking into the source, there's also a Path._flavour.sep attribute:
>>> str(my_path) + my_path._flavour.sep
'abc/def/'
But it doesn't seem to have any documented accessor yet.
You could also use:
os.path.normpath(str(my_path)) + os.sep
I would say it is down to preference rather than being "nicer"
I have a string from which I would like to extract certain part. The string looks like :
E:/test/my_code/content/dir/disp_temp_2.hgx
This is a path on a machine for a specific file with extension hgx
I would exactly like to capture "disp_temp_2". The problem is that I used strip function, does not work for me correctly as there are many '/'. Another problem is that, that the above location will change always on the computer.
Is there any method so that I can capture the exact string between the last '/' and '.'
My code looks like:
path = path.split('.')
.. now I cannot split based on the last '/'.
Any ideas how to do this?
Thanks
Use the os.path module:
import os.path
filename = "E:/test/my_code/content/dir/disp_temp_2.hgx"
name = os.path.basename(filename).split('.')[0]
Python comes with the os.path module, which gives you much better tools for handling paths and filenames:
>>> import os.path
>>> p = "E:/test/my_code/content/dir/disp_temp_2.hgx"
>>> head, tail = os.path.split(p)
>>> tail
'disp_temp_2.hgx'
>>> os.path.splitext(tail)
('disp_temp_2', '.hgx')
Standard libs are cool:
>>> from os import path
>>> f = "E:/test/my_code/content/dir/disp_temp_2.hgx"
>>> path.split(f)[1].rsplit('.', 1)[0]
'disp_temp_2'
Try this:
path=path.rsplit('/',1)[1].split('.')[0]
path = path.split('/')[-1].split('.')[0] works.
You can use the split on the other part :
path = path.split('/')[-1].split('.')[0]
Given a path such as "mydir/myfile.txt", how do I find the file's absolute path in Python? E.g. on Windows, I might end up with:
"C:/example/cwd/mydir/myfile.txt"
>>> import os
>>> os.path.abspath("mydir/myfile.txt")
'C:/example/cwd/mydir/myfile.txt'
Also works if it is already an absolute path:
>>> import os
>>> os.path.abspath("C:/example/cwd/mydir/myfile.txt")
'C:/example/cwd/mydir/myfile.txt'
You could use the new Python 3.4 library pathlib. (You can also get it for Python 2.6 or 2.7 using pip install pathlib.) The authors wrote: "The aim of this library is to provide a simple hierarchy of classes to handle filesystem paths and the common operations users do over them."
To get an absolute path in Windows:
>>> from pathlib import Path
>>> p = Path("pythonw.exe").resolve()
>>> p
WindowsPath('C:/Python27/pythonw.exe')
>>> str(p)
'C:\\Python27\\pythonw.exe'
Or on UNIX:
>>> from pathlib import Path
>>> p = Path("python3.4").resolve()
>>> p
PosixPath('/opt/python3/bin/python3.4')
>>> str(p)
'/opt/python3/bin/python3.4'
Docs are here: https://docs.python.org/3/library/pathlib.html
import os
os.path.abspath(os.path.expanduser(os.path.expandvars(PathNameString)))
Note that expanduser is necessary (on Unix) in case the given expression for the file (or directory) name and location may contain a leading ~/(the tilde refers to the user's home directory), and expandvars takes care of any other environment variables (like $HOME).
Install a third-party path module (found on PyPI), it wraps all the os.path functions and other related functions into methods on an object that can be used wherever strings are used:
>>> from path import path
>>> path('mydir/myfile.txt').abspath()
'C:\\example\\cwd\\mydir\\myfile.txt'
Update for Python 3.4+ pathlib that actually answers the question:
from pathlib import Path
relative = Path("mydir/myfile.txt")
absolute = relative.absolute() # absolute is a Path object
If you only need a temporary string, keep in mind that you can use Path objects with all the relevant functions in os.path, including of course abspath:
from os.path import abspath
absolute = abspath(relative) # absolute is a str object
This always gets the right filename of the current script, even when it is called from within another script. It is especially useful when using subprocess.
import sys,os
filename = sys.argv[0]
from there, you can get the script's full path with:
>>> os.path.abspath(filename)
'/foo/bar/script.py'
It also makes easier to navigate folders by just appending /.. as many times as you want to go 'up' in the directories' hierarchy.
To get the cwd:
>>> os.path.abspath(filename+"/..")
'/foo/bar'
For the parent path:
>>> os.path.abspath(filename+"/../..")
'/foo'
By combining "/.." with other filenames, you can access any file in the system.
Today you can also use the unipath package which was based on path.py: http://sluggo.scrapping.cc/python/unipath/
>>> from unipath import Path
>>> absolute_path = Path('mydir/myfile.txt').absolute()
Path('C:\\example\\cwd\\mydir\\myfile.txt')
>>> str(absolute_path)
C:\\example\\cwd\\mydir\\myfile.txt
>>>
I would recommend using this package as it offers a clean interface to common os.path utilities.
You can use this to get absolute path of a specific file.
from pathlib import Path
fpath = Path('myfile.txt').absolute()
print(fpath)
Given a path such as mydir/myfile.txt, how do I find the file's absolute path relative to the current working directory in Python?
I would do it like this,
import os.path
os.path.join( os.getcwd(), 'mydir/myfile.txt' )
That returns '/home/ecarroll/mydir/myfile.txt'
if you are on a mac
import os
upload_folder = os.path.abspath("static/img/users")
this will give you a full path:
print(upload_folder)
will show the following path:
>>>/Users/myUsername/PycharmProjects/OBS/static/img/user
In case someone is using python and linux and looking for full path to file:
>>> path=os.popen("readlink -f file").read()
>>> print path
abs/path/to/file