I was using python 2.6 for a script, but for requirement limitations I have to downgrade my script to python 2.5, how can I get the relative path using python 2.5?
I was previously using:
os.path.relpath(path[, start])
But since this is new from 2.6 I can't use it anymore.
Thanks and regards!
Try Relative paths in Python it should have valuable information to you.
>>> import sys
>>> import os.path
>>> sys.path[0]
'C:\\Python25\\Lib\\idlelib'
>>> os.path.relpath(sys.path[0], "path_to_libs") # if you have python 2.6
>>> os.path.join(sys.path[0], "path_to_libs")
'C:\\Python25\\Lib\\idlelib\\path_to_libs'
EDIT: Found something more http://www.saltycrane.com/blog/2010/03/ospathrelpath-source-code-python-25/
It is a re-implementation by James Gardner:
from posixpath import curdir, sep, pardir, join
def relpath(path, start=curdir):
"""Return a relative version of a path"""
if not path:
raise ValueError("no path specified")
start_list = posixpath.abspath(start).split(sep)
path_list = posixpath.abspath(path).split(sep)
# Work out how much of the filepath is shared by start and path.
i = len(posixpath.commonprefix([start_list, path_list]))
rel_list = [pardir] * (len(start_list)-i) + path_list[i:]
if not rel_list:
return curdir
return join(*rel_list)
Related
I have created a function where it will dynamically create a json file.
Currently i am using pathlib module which can be found in python 3 . However the server that i am deploying my script will only have python 2.7 and below.
The current approach im doing now work perfectly fine with pathlib module. When this was triggered in a higher environment, error im receiving is pathlib module not found. Hence i would go without using pathlib module when locating the base path to inject json content to publish_workbook.json
import json
import os
from os import listdir
from os.path import isfile, join
from pathlib import Path
def createJson():
print("Creating Json File ....... ")
..
..
event_dict = json.loads(_json)
_jsonFile = json.dumps(event_dict, indent = 4, sort_keys=True)
#Convert path to python 2.7 library orusing os.path
base = Path('/home/reporting/job/')
_saveFile = base / ('publish_workbook' + '.json')
print("Saving json file on : " + str(_saveFile))
_saveFile.write_text(_jsonFile)
createJson()
What is the best approach i can go with this ?
Install pathlib2 on the server, which is a backported version of pathlib. It's no longer supported but then neither is Python 2.7.
You'll then only have to change the import line to
from pathlib2 import Path
Just do it as strings. It's actually fewer characters to type. Pathlib has some cool concepts, but I'm not convinced it's a net win. And, of course, for Python 2 you don't have the print function.
base = '/home/reporting/job/'
_saveFile = base + 'publish_workbook.json'
print "Saving json file on : " + _saveFile
_saveFile.write_text(_jsonFile)
I am trying to make it so when this runs it runs the newest version in the list.
Here is the directory I want:
ClockOS:
bootLoader.py (the file I am starting at)
Versions:
Version 0.1.1:
main.py (Ignore because tis an older version)
Version 0.1.2:
main.py (The one I want to run/import)
I have tried loading through os.dir, and using sys.path, and adding an empty __init__.py
Anyone know how to get this working?
My code:
import os
import re
import sys
versionList = []
for filename in os.listdir('Versions'):
if filename.startswith('Version'):
versionList.append(filename)
print(f"Loaded {filename}")
def major_minor_micro(version):
major, minor, micro = re.search('(\d+)\.(\d+)\.(\d+)', version).groups()
return int(major), int(minor), int(micro)
latest = str(max(versionList, key=major_minor_micro))
print("Newest Version: ", latest)
os.path.dirname('Versions/'+str(latest))
sys.path.insert(1, latest)
print(sys.path)
import main
Lastly, I need this to work on both windows and linix, if that's possible.
You need to use importlib to do what you want. Here is an example on how to import my_function from a file:
import importlib
spec = importlib.util.spec_from_file_location('some_module_name', filename)
mod = importlib.util.module_from_spec(spec)
spec.loader.exec_module(mod)
mod.my_function(1)
Probably the question is a duplicate of Import arbitrary python source file. (Python 3.3+)
I need to change a file path from MAC to Windows and I was about to just do a simple .replace() of any / with \ but it occurred to me that there may be a better way. So for example I need to change:
foo/bar/file.txt
to:
foo\bar\file.txt
You can use this:
>>> s = '/foo/bar/zoo/file.ext'
>>> import ntpath
>>> import os
>>> s.replace(os.sep,ntpath.sep)
'\\foo\\bar\\zoo\\file.ext'
The pathlib module (introduced in Python 3.4) has support for this:
from pathlib import PureWindowsPath, PurePosixPath
# Windows -> Posix
win = r'foo\bar\file.txt'
posix = str(PurePosixPath(PureWindowsPath(win)))
print(posix) # foo/bar/file.txt
# Posix -> Windows
posix = 'foo/bar/file.txt'
win = str(PureWindowsPath(PurePosixPath(posix)))
print(win) # foo\bar\file.txt
Converting to Unix:
import os
import posixpath
p = "G:\Engineering\Software_Development\python\Tool"
p.replace(os.sep, posixpath.sep)
This will replace the used-os separator to Unix separator.
Converting to Windows:
import os
import ntpath
p = "G:\Engineering\Software_Development\python\Tool"
p.replace(os.sep, ntpath.sep)
This will replace the used-os separator to Windows separator.
os.path.join will intelligently join strings to form filepaths, depending on your OS-type (POSIX, Windows, Mac OS, etc.)
Reference: http://docs.python.org/library/os.path.html#os.path.join
For your example:
import os
print os.path.join("foo", "bar", "file.txt")
since path is actually a string, you can simply use following code:
p = '/foo/bar/zoo/file.ext'
p = p.replace('/', '\\')
output:
'\\foo\\bar\\zoo\\file.ext'
How do I get the current file's directory path?
I tried:
>>> os.path.abspath(__file__)
'C:\\python27\\test.py'
But I want:
'C:\\python27\\'
The special variable __file__ contains the path to the current file. From that we can get the directory using either pathlib or the os.path module.
Python 3
For the directory of the script being run:
import pathlib
pathlib.Path(__file__).parent.resolve()
For the current working directory:
import pathlib
pathlib.Path().resolve()
Python 2 and 3
For the directory of the script being run:
import os
os.path.dirname(os.path.abspath(__file__))
If you mean the current working directory:
import os
os.path.abspath(os.getcwd())
Note that before and after file is two underscores, not just one.
Also note that if you are running interactively or have loaded code from something other than a file (eg: a database or online resource), __file__ may not be set since there is no notion of "current file". The above answer assumes the most common scenario of running a python script that is in a file.
References
pathlib in the python documentation.
os.path - Python 2.7, os.path - Python 3
os.getcwd - Python 2.7, os.getcwd - Python 3
what does the __file__ variable mean/do?
Using Path from pathlib is the recommended way since Python 3:
from pathlib import Path
print("File Path:", Path(__file__).absolute())
print("Directory Path:", Path().absolute()) # Directory of current working directory, not __file__
Note: If using Jupyter Notebook, __file__ doesn't return expected value, so Path().absolute() has to be used.
In Python 3.x I do:
from pathlib import Path
path = Path(__file__).parent.absolute()
Explanation:
Path(__file__) is the path to the current file.
.parent gives you the directory the file is in.
.absolute() gives you the full absolute path to it.
Using pathlib is the modern way to work with paths. If you need it as a string later for some reason, just do str(path).
Try this:
import os
dir_path = os.path.dirname(os.path.realpath(__file__))
import os
print(os.path.dirname(__file__))
I found the following commands return the full path of the parent directory of a Python 3 script.
Python 3 Script:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from pathlib import Path
#Get the absolute path of a Python3.6 and above script.
dir1 = Path().resolve() #Make the path absolute, resolving any symlinks.
dir2 = Path().absolute() #See #RonKalian answer
dir3 = Path(__file__).parent.absolute() #See #Arminius answer
dir4 = Path(__file__).parent
print(f'dir1={dir1}\ndir2={dir2}\ndir3={dir3}\ndir4={dir4}')
REMARKS !!!!
dir1 and dir2 works only when running a script located in the current working directory, but will break in any other case.
Given that Path(__file__).is_absolute() is True, the use of the .absolute() method in dir3 appears redundant.
The shortest command that works is dir4.
Explanation links: .resolve(), .absolute(), Path(file).parent().absolute()
USEFUL PATH PROPERTIES IN PYTHON:
from pathlib import Path
#Returns the path of the current directory
mypath = Path().absolute()
print('Absolute path : {}'.format(mypath))
#if you want to go to any other file inside the subdirectories of the directory path got from above method
filePath = mypath/'data'/'fuel_econ.csv'
print('File path : {}'.format(filePath))
#To check if file present in that directory or Not
isfileExist = filePath.exists()
print('isfileExist : {}'.format(isfileExist))
#To check if the path is a directory or a File
isadirectory = filePath.is_dir()
print('isadirectory : {}'.format(isadirectory))
#To get the extension of the file
fileExtension = mypath/'data'/'fuel_econ.csv'
print('File extension : {}'.format(filePath.suffix))
OUTPUT:
ABSOLUTE PATH IS THE PATH WHERE YOUR PYTHON FILE IS PLACED
Absolute path : D:\Study\Machine Learning\Jupitor Notebook\JupytorNotebookTest2\Udacity_Scripts\Matplotlib and seaborn Part2
File path : D:\Study\Machine Learning\Jupitor Notebook\JupytorNotebookTest2\Udacity_Scripts\Matplotlib and seaborn Part2\data\fuel_econ.csv
isfileExist : True
isadirectory : False
File extension : .csv
works also if __file__ is not available (jupyter notebooks)
import sys
from pathlib import Path
path_file = Path(sys.path[0])
print(path_file)
Also uses pathlib, which is the object oriented way of handling paths in python 3.
IPython has a magic command %pwd to get the present working directory. It can be used in following way:
from IPython.terminal.embed import InteractiveShellEmbed
ip_shell = InteractiveShellEmbed()
present_working_directory = ip_shell.magic("%pwd")
On IPython Jupyter Notebook %pwd can be used directly as following:
present_working_directory = %pwd
I have made a function to use when running python under IIS in CGI in order to get the current folder:
import os
def getLocalFolder():
path=str(os.path.dirname(os.path.abspath(__file__))).split(os.sep)
return path[len(path)-1]
Python 2 and 3
You can simply also do:
from os import sep
print(__file__.rsplit(sep, 1)[0] + sep)
Which outputs something like:
C:\my_folder\sub_folder\
This can be done without a module.
def get_path():
return (__file__.replace(f"<your script name>.py", ""))
print(get_path())
Could someone tell me how to get the parent directory of a path in Python in a cross platform way. E.g.
C:\Program Files ---> C:\
and
C:\ ---> C:\
If the directory doesn't have a parent directory, it returns the directory itself. The question might seem simple but I couldn't dig it up through Google.
Python 3.4
Use the pathlib module.
from pathlib import Path
path = Path("/here/your/path/file.txt")
print(path.parent.absolute())
Old answer
Try this:
import os
print os.path.abspath(os.path.join(yourpath, os.pardir))
where yourpath is the path you want the parent for.
Using os.path.dirname:
>>> os.path.dirname(r'C:\Program Files')
'C:\\'
>>> os.path.dirname('C:\\')
'C:\\'
>>>
Caveat: os.path.dirname() gives different results depending on whether a trailing slash is included in the path. This may or may not be the semantics you want. Cf. #kender's answer using os.path.join(yourpath, os.pardir).
The Pathlib method (Python 3.4+)
from pathlib import Path
Path('C:\Program Files').parent
# Returns a Pathlib object
The traditional method
import os.path
os.path.dirname('C:\Program Files')
# Returns a string
Which method should I use?
Use the traditional method if:
You are worried about existing code generating errors if it were to use a Pathlib object. (Since Pathlib objects cannot be concatenated with strings.)
Your Python version is less than 3.4.
You need a string, and you received a string. Say for example you have a string representing a filepath, and you want to get the parent directory so you can put it in a JSON string. It would be kind of silly to convert to a Pathlib object and back again for that.
If none of the above apply, use Pathlib.
What is Pathlib?
If you don't know what Pathlib is, the Pathlib module is a terrific module that makes working with files even easier for you. Most if not all of the built in Python modules that work with files will accept both Pathlib objects and strings. I've highlighted below a couple of examples from the Pathlib documentation that showcase some of the neat things you can do with Pathlib.
Navigating inside a directory tree:
>>> p = Path('/etc')
>>> q = p / 'init.d' / 'reboot'
>>> q
PosixPath('/etc/init.d/reboot')
>>> q.resolve()
PosixPath('/etc/rc.d/init.d/halt')
Querying path properties:
>>> q.exists()
True
>>> q.is_dir()
False
import os
p = os.path.abspath('..')
C:\Program Files ---> C:\\\
C:\ ---> C:\\\
An alternate solution of #kender
import os
os.path.dirname(os.path.normpath(yourpath))
where yourpath is the path you want the parent for.
But this solution is not perfect, since it will not handle the case where yourpath is an empty string, or a dot.
This other solution will handle more nicely this corner case:
import os
os.path.normpath(os.path.join(yourpath, os.pardir))
Here the outputs for every case that can find (Input path is relative):
os.path.dirname(os.path.normpath('a/b/')) => 'a'
os.path.normpath(os.path.join('a/b/', os.pardir)) => 'a'
os.path.dirname(os.path.normpath('a/b')) => 'a'
os.path.normpath(os.path.join('a/b', os.pardir)) => 'a'
os.path.dirname(os.path.normpath('a/')) => ''
os.path.normpath(os.path.join('a/', os.pardir)) => '.'
os.path.dirname(os.path.normpath('a')) => ''
os.path.normpath(os.path.join('a', os.pardir)) => '.'
os.path.dirname(os.path.normpath('.')) => ''
os.path.normpath(os.path.join('.', os.pardir)) => '..'
os.path.dirname(os.path.normpath('')) => ''
os.path.normpath(os.path.join('', os.pardir)) => '..'
os.path.dirname(os.path.normpath('..')) => ''
os.path.normpath(os.path.join('..', os.pardir)) => '../..'
Input path is absolute (Linux path):
os.path.dirname(os.path.normpath('/a/b')) => '/a'
os.path.normpath(os.path.join('/a/b', os.pardir)) => '/a'
os.path.dirname(os.path.normpath('/a')) => '/'
os.path.normpath(os.path.join('/a', os.pardir)) => '/'
os.path.dirname(os.path.normpath('/')) => '/'
os.path.normpath(os.path.join('/', os.pardir)) => '/'
os.path.split(os.path.abspath(mydir))[0]
os.path.abspath(os.path.join(somepath, '..'))
Observe:
import posixpath
import ntpath
print ntpath.abspath(ntpath.join('C:\\', '..'))
print ntpath.abspath(ntpath.join('C:\\foo', '..'))
print posixpath.abspath(posixpath.join('/', '..'))
print posixpath.abspath(posixpath.join('/home', '..'))
import os
print"------------------------------------------------------------"
SITE_ROOT = os.path.dirname(os.path.realpath(__file__))
print("example 1: "+SITE_ROOT)
PARENT_ROOT=os.path.abspath(os.path.join(SITE_ROOT, os.pardir))
print("example 2: "+PARENT_ROOT)
GRANDPAPA_ROOT=os.path.abspath(os.path.join(PARENT_ROOT, os.pardir))
print("example 3: "+GRANDPAPA_ROOT)
print "------------------------------------------------------------"
>>> import os
>>> os.path.basename(os.path.dirname(<your_path>))
For example in Ubuntu:
>>> my_path = '/home/user/documents'
>>> os.path.basename(os.path.dirname(my_path))
# Output: 'user'
For example in Windows:
>>> my_path = 'C:\WINDOWS\system32'
>>> os.path.basename(os.path.dirname(my_path))
# Output: 'WINDOWS'
Both examples tried in Python 2.7
Suppose we have directory structure like
1]
/home/User/P/Q/R
We want to access the path of "P" from the directory R then we can access using
ROOT = os.path.abspath(os.path.join("..", os.pardir));
2]
/home/User/P/Q/R
We want to access the path of "Q" directory from the directory R then we can access using
ROOT = os.path.abspath(os.path.join(".", os.pardir));
If you want only the name of the folder that is the immediate parent of the file provided as an argument and not the absolute path to that file:
os.path.split(os.path.dirname(currentDir))[1]
i.e. with a currentDir value of /home/user/path/to/myfile/file.ext
The above command will return:
myfile
import os
dir_path = os.path.dirname(os.path.realpath(__file__))
parent_path = os.path.abspath(os.path.join(dir_path, os.pardir))
import os.path
os.path.abspath(os.pardir)
Just adding something to the Tung's answer (you need to use rstrip('/') to be more of the safer side if you're on a unix box).
>>> input1 = "../data/replies/"
>>> os.path.dirname(input1.rstrip('/'))
'../data'
>>> input1 = "../data/replies"
>>> os.path.dirname(input1.rstrip('/'))
'../data'
But, if you don't use rstrip('/'), given your input is
>>> input1 = "../data/replies/"
would output,
>>> os.path.dirname(input1)
'../data/replies'
which is probably not what you're looking at as you want both "../data/replies/" and "../data/replies" to behave the same way.
print os.path.abspath(os.path.join(os.getcwd(), os.path.pardir))
You can use this to get the parent directory of the current location of your py file.
GET Parent Directory Path and make New directory (name new_dir)
Get Parent Directory Path
os.path.abspath('..')
os.pardir
Example 1
import os
print os.makedirs(os.path.join(os.path.dirname(__file__), os.pardir, 'new_dir'))
Example 2
import os
print os.makedirs(os.path.join(os.path.dirname(__file__), os.path.abspath('..'), 'new_dir'))
os.path.abspath('D:\Dir1\Dir2\..')
>>> 'D:\Dir1'
So a .. helps
import os
def parent_filedir(n):
return parent_filedir_iter(n, os.path.dirname(__file__))
def parent_filedir_iter(n, path):
n = int(n)
if n <= 1:
return path
return parent_filedir_iter(n - 1, os.path.dirname(path))
test_dir = os.path.abspath(parent_filedir(2))
The answers given above are all perfectly fine for going up one or two directory levels, but they may get a bit cumbersome if one needs to traverse the directory tree by many levels (say, 5 or 10). This can be done concisely by joining a list of N os.pardirs in os.path.join. Example:
import os
# Create list of ".." times 5
upup = [os.pardir]*5
# Extract list as arguments of join()
go_upup = os.path.join(*upup)
# Get abspath for current file
up_dir = os.path.abspath(os.path.join(__file__, go_upup))
To find the parent of the current working directory:
import pathlib
pathlib.Path().resolve().parent
import os
def parent_directory():
# Create a relative path to the parent of the current working directory
relative_parent = os.path.join(os.getcwd(), "..") # .. means parent directory
# Return the absolute path of the parent directory
return os.path.abspath(relative_parent)
print(parent_directory())