is there a function that translate relative path ../test.txt into a full path?
example:
the full path is:
/Users/paganotti/Documents/Project/simple/work/paga/
the relative path is:
../test.txt
I want build this result:
/Users/paganotti/Documents/Project/simple/work/test.txt
As you can see translate ../ into "work" folder for build entire path.
Is there general function that acomplish this task?
use this:
import os
os.path.abspath('../test.txt')
Documentation
You can use normpath() from the os.path module to get a normalize path from one with ".." and similar constructs:
base = '/Users/paganotti/Documents/Project/simple/work/paga/'
rel = '../test.txt'
print os.path.normpath(os.path.join(base, rel))
Related
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
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.
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 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
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